lewis4u lewis4u - 28 days ago 19
jQuery Question

Checkbox not closing paragraph

I can't figure it out why is this not working:

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
if ($('#check').is(':checked')) {
$('p').hide();
} else {
$('p').show();
}
});
</script>
</head>
<body>
<input type="checkbox" id="check" />
<p>If you click on the checkbox, I will disappear.</p>
</body>
</html>


Fiddle

When i click on the checkbox it should hide the p tag but it doesn't...
This should be so simple, but then again it is not :(

Answer

You're only running your code on load of the page. You need to add a change event handler to your checkbox. Also note that you can simplify the code by passing the checked property value to the toggle() method:

$(document).ready(function() {
  $('#check').change(function() {
    $('p').toggle(!this.checked);
  }).change();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="check" />
<p>If you click on the checkbox, I will disappear.</p>