Dedi Ananto Dedi Ananto - 6 months ago 28
HTML Question

JQuery - Hide parent div if child div haven't similar or like data attribute

i want to hide country name when user type airport and the country don't have similar airport name.



$(document).ready(function() {
$('#from').focus();
$('#from').on( "keyup", function() {
$(".wrap-airport-from").animate({ scrollTop: 0 }, "fast");
if($(this).val()) {
var input = $(this).val().toLowerCase();
console.log(input);
//alert(input);
$(".airport-from").hide();
$(".airport-from[data-kode*='"+ input +"']").show();
}else{
$(".airport-from").show();
}
});
});

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="from">
<div class="wrap-airport-from">
<div class="list-country">
<b>Indonesia</b>
<div class="list-airport">
<a href="#" class="airport-from" data-kode="jakarta">Jakarta</a>
</div>
</div>
<div class="list-country">
<b>Australia</b>
<div class="list-airport">
<a href="#" class="airport-from" data-kode="sidney">Sidney</a>
</div>
</div>
</div>





above code only hide airport name and still show country

Answer

You can use jQuery function .parents() to select and hide the corresponding parent element.

$(document).ready(function() {
  $('#from').focus();
  $('#from').on("keyup", function() {
    $(".wrap-airport-from").animate({
      scrollTop: 0
    }, "fast");
    if ($(this).val()) {
      var input = $(this).val().toLowerCase();
      console.log(input);
      //alert(input);
      $(".airport-from").hide();
      $(".airport-from").parents('.list-country').hide();
      $(".airport-from[data-kode*='" + input + "']").parents('.list-country').show();
      $(".airport-from[data-kode*='" + input + "']").show();
    } else {
      $(".airport-from").show();
      $(".airport-from").parents('.list-country').show();
    }
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="from">
<div class="wrap-airport-from">
  <div class="list-country">
    <b>Indonesia</b>
    <div class="list-airport">
      <a href="#" class="airport-from" data-kode="jakarta">Jakarta</a>
    </div>
  </div>
  <div class="list-country">
    <b>Australia</b>
    <div class="list-airport">
      <a href="#" class="airport-from" data-kode="sidney">Sidney</a>
    </div>
  </div>
</div>