Show/Hide div when checkbox selected

user2890036 picture user2890036 · Oct 18, 2013 · Viewed 66k times · Source

I need to make additional content appear when a user selects a checkbox. I have the following code:

<!DOCTYPE html>
<html>
<head>
<title>Checkbox</title>
<script type="text/javascript">


$(document).ready(function(){
$('#checkbox1').change(function(){
if(this.checked)
$('#autoUpdate').fadeIn('slow');
else
$('#autoUpdate').fadeOut('slow');

});
});

</script>
</head>
<body>
Add another director <input type="checkbox" id="checkbox1"/>
<div id="autoUpdate" class="autoUpdate">
content
</div>
</body>
</html>

Would really appreciate some help, good knowledge of HTML5, CSS3 but very basic JavaScript/jQuery.

Answer

Anton picture Anton · Oct 18, 2013

You are missing jQuery in your head you must include it.

<script src="http://code.jquery.com/jquery-1.9.1.js"></script>

Your code works DEMO

Update according to new info

$(document).ready(function () {
    $('#checkbox1').change(function () {
        if (!this.checked) 
        //  ^
           $('#autoUpdate').fadeIn('slow');
        else 
            $('#autoUpdate').fadeOut('slow');
    });
});

DEMO

You can also just use .fadeToggle()

$(document).ready(function () {
    $('#checkbox1').change(function () {
      $('#autoUpdate').fadeToggle();
    });
});