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.
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.
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;
}
.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.