Show Div with jquery depending on list (php)

Viewed 209

I have read how to show/hide a div with jquery when there is a dropdown selection, built with "select" and options.

However, I am trying to figure out how to do this when I have the following code for a dropdown selection.

<?php echo $this->lists['catid']; ?>

This list displays a dropdown of options and I want for a specific option to show/hide a div.

The following code could work for a select with a specific id,"purpose", for example, but in my situation how I am supposed to use it?

$('#catid').on('change', function() {
  if ( this.value == '37');
  {
    $("#business").show();
  }
  else
  {
    $("#business").hide();
  }
});
})

This is the html of the output of the php code

This is the html of the output of the php code

Thank you

3 Answers

You can loop through each option and check the value. If the value is 37, then show that option (or any other div that you want to show):

$('#catid').on('change', function() {
    $('#catid option').each(function() {
        if ($(this).val() === '37') {
            $(this).show()
        } else {
            $(this).hide()
        }
    })
})

NOTE: You can replace $(this) with the element/div that you want to show/hide if you want to show/hide something else.

Working JSFiddle here.

Try code should work for you

$(document).ready(function(event) {
  $('#catid').on('change', function() {
    let selected = $('#catid').val();
    if (selected == 37) {
      $("#business").show();
    } else {
      $("#business").hide();
    }
  });
});
#business {
  display: none;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.4.1/jquery.min.js"></script>
<select id="catid">
  <option value="38">option 38(hide)</option>
  <option value="37">option 37(show)</option>
  <option value="39">option 39(hide)</option>
</select>
<div id="business">
  Division Visible!
</div>

$('#purpose').on('change', function() {   
    if (this.value == '37')
    { 
        $("#business").css('display','');
    }
    else
    {
        $("#business").css('display','none');
    }
});


 You also use this ans 

$('#purpose').on('change', function() {   
    if (this.value == '37')
    { 
        $("#business").show();
    }
    else
    {
        $("#business").hide();
    }
});
Related