Stinky Tofu
Stinky Tofu

Reputation: 475

JQuery and multiple radio button groups problem

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!

Upvotes: 1

Views: 5968

Answers (2)

Christian C. Salvad&#243;
Christian C. Salvad&#243;

Reputation: 827396

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
  }
});

Upvotes: 8

Doug Neiner
Doug Neiner

Reputation: 66191

A small change will fix it:

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

Upvotes: 3

Related Questions