Kelvin Halim Kelvin Halim - 6 months ago 8
jQuery Question

how to show or hide dropdown, if chekbox is checked

hello guys (: can you help me how to show or hide my option if check box is not checked

this is the code

<label>Busy</label>:</label><br><br>
<div class="checkbox checkbox-info">
<input type="checkbox" name="busy" id="busy" value="busy">
<label for="busy">Busy</label>
</div><br>
<div id="dropdownHolder">
<label>Add Time</label>:
<div class="row">
<div class="col-md-6">
<select id="time">
<option value = "30min">30 minute</option>
<option value ="1hr">1 hour</option>
<option value ="1hr30min">1 hour 30minute</option>
<option value ="2hr">2 hour</option>
</select>
</div>
</div>
</div>


this the jQuery

<script type="text/javascript">

$(function(){

//initially all dropdowns are hidden
$('#dropdownHolder select').hide();
$('input:checkbox').click(function(){
var isOnCall = $('.OnCall:checked').length,
anyOther = $('.other:checked').length;
$('#dropdownHolder select').hide();
if (isOnCall > 0 && anyOther > 0){
$('#time').show();
}

})


});
</script>


that jquery is not mine i am just copy paste it. i can't show the option menu when even i have check the box can you help me how to solve this?

Answer

$('#dropdownHolder select').hide(); //initially dropdown is hidden
$('#busy').change(function() { //change click to hidden

  if ($(this).is(':checked')) { //check if checkbox is checked
    $('#dropdownHolder select').show(); //show if checked
  } else {
    $('#dropdownHolder select').hide(); //hide if unchecked
  }

})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<label>Busy</label>:</label>
<br>
<br>
<div class="checkbox checkbox-info">
  <input type="checkbox" name="busy" id="busy" value="busy">
  <label for="busy">Busy</label>
</div>
<br>
<div id="dropdownHolder">
  <label>Add Time</label>:
  <div class="row">
    <div class="col-md-6">
      <select id="time">
        <option value="30min">30 minute</option>
        <option value="1hr">1 hour</option>
        <option value="1hr30min">1 hour 30minute</option>
        <option value="2hr">2 hour</option>
      </select>
    </div>
  </div>
</div>

  1. Change the event click to change event. When using checkbox it is better to use change event.
  2. if (isOnCall > 0 && anyOther > 0){ This condition is not needed maybe a mistake from copy paste.
  3. TO check if the checkbox is checked you can use $(':checkbox').is(':checked') condition
Comments