tags:

views:

303

answers:

2

I am having trouble using JQuery to work with multiple radio button groups. The JQuery code, for some reason, cannot tell the difference between the two groups of radio buttons and cannot tell which group of radio button I clicked on.

Here is the HTML code:

<!-- Radio button group 1 -->
<input type="radio" name="group_1" value="full_day_ticket"/>
<input type="radio" name="group_1" value="half_day_ticket"/>

<!-- Radio button group 2 -->
<label><input type="radio" name="group_2" value="boarder"/> Snowboard</label>
<label><input type="radio" name="group_2" value="skier"/> Ski</label>

And the JQuery code is as follows:

$("input:radio[@name='group_2']").click(function() {
  alert('group 2 clicked');
}

Now when I click on the radio buttons named 'group_1', JQuery thinks that I clicked on a radio button in 'group_2' and displays the alert window. For some reason, it seems that JQuery is not recognising the @name='group_2' filter and captures clicks on all radio buttons on the page, instead of just the radio buttons named 'group_2'.

Has anyone come across this problem before? Or am I doing something stupid?

Thanks!

+1  A: 

A small change will fix it:

$("input:radio[name=group_2]").click(function() {
  alert('group 2 clicked');
});
Doug Neiner
Thanks, but removing the single quotes didn't work. When I click on the group_1 radio buttons, the group_2 alert message still pops up.
Stinky Tofu
Doh! Never mind. I didn't notice that you removed the @ from the @name. Removing the @ resolved the problem! Thanks!
Stinky Tofu
+3  A: 

Be aware that in jQuery 1.3 [@attr] style selectors were removed.

The selector will work as expected if you remove the @ sign.

But you could actually handle the click event for both groups:

$("input:radio").click(function() {
  if (this.name == "group_1") {
    // group 1 clicked
  } else if (this.name == "group_2") {
    // group 2 clicked
  }
});
CMS
+1 For explaining about the deprecation. And great code example. :)
Doug Neiner
Thanks dcneiner, the @attr selectors were *deprecated* on 1.2 and completely removed on 1.3
CMS