mike3875 mike3875 - 6 months ago 11
Javascript Question

Hide parent element

Here is my HTML;

<div class="pagination__page" data-pagination-page="" data-pagination-group="group-0" style="display: block;">
<div class="question">
<h2 class="question__title">Country</h2>
<div class="form-field form-field--dropdown">
<select required="1" name="country" data-parsley-group="group-0">
<option selected="selected" value="">Please select...</option>
<option value="great-britain">Great Britain</option>
<option value="zimbabwe">Zimbabwe</option>
</select>
</div>
</div>

<div class="question"> // line 13
<h2 class="question__title">Postcode</h2>
<div class="form-field">
<input data-parsley-postcode="1" name="postcode" type="text" data-parsley-group="group-0">
</div>
</div>
</div>


How can I hide the div starting on "line 13" (see comment in code) unless the Country question above's input is Great Britain?

It's dynamic so I can't assign the div directly to give it a name. All I have to go on is the
input
which has name of
postcode
.

If I could access that div, then I think it would be something like;

$('#country').on('change.postcode', function() {
$("#").toggle($(this).val() == 'great-britain');
}).trigger('change.postcode');

Answer

A combination of parent and next should do the trick:

$(function(){
 $('select[name="country"]').change(function(){
     var country = $(this).val();
   if(country == 'great-britain'){
      $(this).parent().parent().next('.question').show();
   }
   else{
        $(this).parent().parent().next('.question').hide();
   }
 });
});

In order to hide the dinamically generated html, you can do something like this:

$('.question').each(function(i,item){
    if((i+1) % 2 ==0){
    $(item).hide();
  }
});

Updated fiddle: https://jsfiddle.net/robertrozas/pen942nf/1/

Comments