Reputation: 405
I have a javascript code to show a field when a radio button is check. The code works perfectly, but when I uncheck the radio, the field doesn't hide. It also shows a <span>
when the radio button is checked, but when it's unchecked, also the span doesn't hide..
<script>
$(function() {
$('#radiopromo2').live('change', function() {
if($(this).is(':checked')) {
$("#fieldtraining").show();
$("#radio3").show();
} else {
$("#fieldtraining").hide();
$("#radio3").hide();
}
}).trigger('change');
});
</script>
Anyone who can help me? I made a jsfiddle http://jsfiddle.net/4UH2H/8/
Upvotes: 2
Views: 1294
Reputation: 16369
Try using the more appropriate .prop():
if($(this).prop('checked')){
Or even plain old Javascript (it's way faster):
if(this.checked){
That always works for me. Also, .live()
is deprecated in favor of .on()
, and for radio buttons it is better to use click
instead of change
because of an older webkit version bug not recognizing onchange properly:
$('#radiopromo2').on('click',function(){
With these changes you should be golden.
EDIT Based on the jsFiddle here, you're event wasn't fired with the correct selector. Here is the updated stuff:
$('input[name="radiotraining"]').on('click', function () {
if ($('#radiopromo2').prop('checked')) {
$("#fieldtraining").show();
$("#radio3").show();
} else {
$("#fieldtraining").hide();
$("#radio3").hide();
}
});
It works! yay! Although looking at your jsFiddle, you really should consider using CSS instead of jQuery for such basic show/hide stuff:
#fieldtraining,#radio3 {
display:none;
}
#radiopromo2:checked + #radio2 > #radio3 {
display:inline;
}
#radiopromo2:checked ~ #fieldtraining {
display:block;
}
Would work perfectly fine with IE9+ and all real browsers (yay CSS3!), would be way faster than JS, and would work even when greyhairs turn off JS on their browsers. You can save the jQuery for those lame old browsers like IE6. Here is the jsFiddle to show what I mean.
Upvotes: 5
Reputation: 354
the behavior of .is() method in jquery is not as expected.Instead of .is() use .attr():
if($(this).attr("checked") == "checked")){
// code goes here
}
Upvotes: 0