选中复选框时显示/隐藏div

时间:2013-10-18 10:38:25

标签: javascript jquery html checkbox show-hide

当用户选中复选框时,我需要显示其他内容。我有以下代码:

<!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>

非常感谢HTML5,CSS3以及非常基本的JavaScript / jQuery的一些帮助,知识。

3 个答案:

答案 0 :(得分:14)

你缺少jQuery,你必须包括它。

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

您的代码有效DEMO

根据新信息进行更新

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

DEMO

您也可以使用.fadeToggle()

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

答案 1 :(得分:3)

首先包括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>

参见 demo

参考:checkedis()

答案 2 :(得分:0)

请用下面的代码替换你的代码

<!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>