Show/Hide div when checkbox selected [closed]

99封情书 提交于 2019-12-17 19:53:05

问题


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.


回答1:


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();
    });
});



回答2:


first in head include jquery

<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
<script type="text/javascript">
    $(document).ready(function(){
    $('#checkbox1').change(function(){
    if($(this).is(":checked"))
    $('#autoUpdate').fadeIn('slow');
    else
    $('#autoUpdate').fadeOut('slow');

    });
    });
</script>

see demo

reference :checked and is()




回答3:


Plese replace your code with below it will help you

<!DOCTYPE html>
<html>
<head>
<title>Checkbox</title>
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<script type="text/javascript">


$(document).ready(function(){
$('#checkbox1').change(function(){
if(this.is(":checked") == true)
$('#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>


来源:https://stackoverflow.com/questions/19447591/show-hide-div-when-checkbox-selected

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!