kosherjellyfish
kosherjellyfish

Reputation: 373

Why does my jQuery script run only once?

I have radio buttons that simply have "YES" and "NO" as options.

<input name="paperAvailable" type="radio" value="Yes" /> Yes
<input name="paperAvailable" type="radio" value="No"> No

I wish to hide a couple of table rows (under the class name 'paperavailable' with jQuery script when the option "No" is selected, and show the rows again when the user select 'Yes'

Somehow, the function only seem to work once on page load. Is it because I placed the functions in the document.ready function?

$(document).ready(function(){

$('.paperavailable').hide();


//Paper Available columns
$("input[name='paperAvailable']").click(function() {
    if ($("input[name='paperAvailable']").val() == "YES") { 
        $(".paperavailable").show();
    }

    else { 
    $(".paperavailable").hide("slow");
        }

});

});

Upvotes: 0

Views: 79

Answers (1)

Arun P Johny
Arun P Johny

Reputation: 388316

2 problems

  1. The string comparison is case sensitive - you have the value set to Yes, but in comparison you are testing against YES
  2. $("input[name='paperAvailable']").val() will always return the value of first input element with name paperAvailable, instead you need to get the value of the checked element

you need to test the checked radio box

$(document).ready(function () {
    var $paper = $('.paperavailable').hide();
    //Paper Available columns
    var $radios = $("input[name='paperAvailable']").click(function () {
        if ($radios.filter(':checked').val() == "Yes") {
            $paper.show();
        } else {
            $paper.hide("slow");
        }
    });
});

Demo: Fiddle

Upvotes: 2

Related Questions