Ayanize Ayanize - 5 months ago 8
jQuery Question

Show or hide Div based on the checkbox value

I want to display a div based on the checkbox value. I tried the following

$(document).ready(function () {
$('#parent').change(function () {
if (this.checked) {
$('#child').css('display', 'block');
}
else {
$('#child').css('display', 'none');
}
});


});

Now it's working if I check the
#parent
checkbox. But the problem is the checkbox is in a form. Next time I refresh the page,even though the checkbox is checked, it still displays none.

How to checked this displayed if the checkbox is checked or else display none.

Thanks

Answer

Trigger the change event using change() or trigger('change') method

$(document).ready(function() {
  $('#parent').change(function() {
    if (this.checked) {
      $('#child').css('display', 'block');
    } else {
      $('#child').css('display', 'none');
    }
  }).change();
});

Also you can reduce the code using toggle() method.

$(document).ready(function() {
  $('#parent').change(function() {
    $('#child').toggle(this.checked);
  }).change();
});