Reputation: 1036
I have a problem with this jQuery Change function:
<input type="radio" name="words" value="8" checked><span class="word">word1</span>
<input type="radio" name="words" value="6"><span class="word">word2</span>
$("input[@name='words']:checked").change(function(){
alert("test");
});
The problem is that the event gets only triggered when I click the first option (value=8) which is checked by default.
How Can I trigger the event when clicking any other option?
Please note: I have tried the above function on both Chrome and Firefox and I have the same problem.
Thanks!
Upvotes: 1
Views: 6495
Reputation: 21
In jquery CheckClick() function
if ($('#rb2').attr('checked')) { alert('rb2 test'); }
Upvotes: 1
Reputation: 30115
$("input[@name='words']:checked").change(function(){
alert("test");
});
You've subscribed change function only to the radiobuttons whitch is checked (:checked
). Remove it from selector.
$("input[name='words']").change(function(){
alert("test");
});
Code: http://jsfiddle.net/DRasw/1/
Upvotes: 1
Reputation: 237865
$("input[@name='words']:checked").change(function(){
That finds all the input
elements with the name words
(actually, it won't work: the XPath-style @
attribute selector has been removed since jQuery 1.3) that are checked and binds an event handler to them. If the elements are not checked when the selection is made, no event handlers will be bound to them.
The easiest solution is to bind to all relevant elements, and only fire code if they have been unchecked:
$('input[name="words"]').change(function() {
if (!this.checked) { // checkbox was checked, now is not
alert('unchecked');
}
});
Upvotes: 1
Reputation: 165971
You are only binding the event handler to :checked
elements. So as the first input
has the checked
property set, that's the only one that receives the event handler. Remove :checked
and it should work fine:
$("input[name='words']").change(function(){
alert("test");
});
Here's a working example. Note that I've also removed the @
character from your selector. You haven't needed it since like jQuery 1.2 or something like that.
Upvotes: 1