Show another option when checkbox is selected

Go To StackoverFlow.com

1

I am having trouble trying to show "T-Shirt" sizes when a checkbox is selected. I am using jQuery but I am not able to get the code to work properly. Here is my code so far:

<script type="text/javascript">
    $(document).ready(function(){
        $('#tshirt').attr('checked'); 
        $("#sizes").show();
    });
);
</script>


<b>Cool T-Shirt</b>: <input type="checkbox" id="tshirt" name="tshirt"> <span class="price">$15</span>            
<span id="sizes"><bSize</b>: <input type="checkbox" name="size" value="S"> <span class="price">Small</span></span>

Currently the ID "sizes" is set to display: none via CSS. What I am having difficulty with is when a user selects the checkbox with the ID "tshirt", I want the ID "sizes" to be displayed.

2012-04-04 00:30
by three3


2

You need to put your code inside a click() handler, like this:

$(document).ready(function () {
    $('input#tshirt').click(function () {
        if($(this).is(':checked')) {
            $("#sizes").show();
        } else {
            $("#sizes").hide();
        }
    });
});

This will show #sizes when the checkbox is checked, and will hide them again when it's un-checked.

It's unclear why you have $('#tshirt').attr('checked'); in your current JS, as you can simply add checked="checked" to your <input> to make it checked on page load.

2012-04-04 00:34
by Bojangles


2

You should be able to do something like this:

$(document).ready(function() {
    $("#tshirt").change(function() {
        if($(this).is(":checked")) {
             $("#sizes").show();
        } else {
             $("#sizes").hide();            
        }
    });
});

Then just make sure is hidden by default with CSS:

#sizes {
    display: none;
}
2012-04-04 00:36
by wows


0

.toggle() should take care of it. Something like this..

$('#tshirt').click(function () {
$('#sizes').toggle('slow', function() {

'slow' you can replace with 'fast' and other parameters.

2012-04-04 00:34
by Ray
This will work, but it's better to check whether the checkbox's state and act based on that; another piece of JS could change the checked state and then you'd get inverse behaviour - Bojangles 2012-04-04 02:07