Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

When Checkbox is Checked Expand Div

I have a checkbox:

<input type="checkbox" name="mycheckbox" id="mycheckbox" value="0" />
<div style="display:none">
This content should appear when the checkbox is checked
</div>

Does anyone have a simple way to do this?

like image 823
Satch3000 Avatar asked Nov 03 '11 14:11

Satch3000


2 Answers

This will show it when the checkbox is checked, and hide it again when the checkbox is unchecked:

$('#mycheckbox').change(function() {
    $(this).next('div').toggle();
});

...although it would be better if you'd assign that DIV an id, so it could be selected more quickly:

<input type="checkbox" name="mycheckbox" id="mycheckbox" value="0" />
<div id="mycheckboxdiv" style="display:none">
    This content should appear when the checkbox is checked
</div>

<script type="text/javascript">
$('#mycheckbox').change(function() {
    $('#mycheckboxdiv').toggle();
});
</script>

http://jsfiddle.net/mblase75/pTA3Y/

If you want to show the div without hiding it again, replace .toggle() with .show().

like image 74
Blazemonger Avatar answered Oct 07 '22 01:10

Blazemonger


Attach a change event, and check whether a checkbox is checked or not. If the checkbox is checked, show the div. Otherwise, hide it:

$('#mycheckbox').change(function(){
    if(this.checked) {
        $(this).next().show();
    } else {
        $(this).next().hide();
    }
});

You should also have a look at the jQuery docs, before asking such a trivial question.

like image 23
Rob W Avatar answered Oct 07 '22 00:10

Rob W