Nat
Nat

Reputation: 61

jquery radio button change not detected by bound function

With the following html:

<input type = "radio" name = "who" class = "number" value = "0" > text </input>
<input type = "radio" name = "who"   class = "number" value = "1" > text </input>
<input type = "radio" name = "numberS"  class = "number"  value = "1" > text </input>
<input type = "radio" name = "numberS"  class = "number"  value = "2" > text</input>

and the following two bits of javascript:

$('input[class="number"]').bind('change', function (){
    alert("Change!");
    })

function change_radio_button(n){
   $('input[class="number"]')[n].checked = true;
   }

As is, this all works perfectly: selecting a new radio button calls the alert, and calling change_radio_button() changes which radio button is selected.

But when change_radio_button() is called and the radio button selection changes, the bound function does not detect the change--the alert doesn't happen. Why not? Does the jquery function only detect manual changes?

Upvotes: 0

Views: 900

Answers (1)

ShankarSangoli
ShankarSangoli

Reputation: 69905

If you have a class then use class selector. Using class as attribute selector is not a best practice.

$('input.number').bind('change', function (){
    alert("Change!");
});

And you want to fire change event use trigger or just call change() method. This event will not be changed when you change the check the radio buttons programmatically.

function change_radio_button(n){
   $('input.number')[n].checked = true;
   $('input.number').trigger('change');
}

Upvotes: 2

Related Questions