views:

2120

answers:

4

I want to use jQuery to detect clicks on a bunch of radio buttons. They have all been assigned a css class, foobar, to detect them. Easy, right? Still, this code doesn't work:

$("input.foobar").click(function ()
{ 
    alert(this.id);
}
);

What wrong with the code above?

Does this.id really return the id of the current radio button?

EDIT: The HTML on the page is really borked (doesn't valdiate), so maybe that's the problem...

EDIT 2: The HTML is messed up beyond salvation. Will have to let it be and fix a workaround. May the HTML Gods forgive me!

+2  A: 
$("input.foobar").change(function () {
    alert(this.id);
});
Koistya Navin
A: 

Essentially there is nothing wrong with your code, it should work. But maybe the html would help, to understand where the problem lies.

And to answer your second question, yes, 'this.id' is valid javascript.

Sander Versluys
A: 

Try

$("input.foobar").change(function ()

rather than .click(function ()

Steerpike
A: 

There is nothing wrong with your code example and it works as expected for me:

<input type="radio" class="foobar" id="x1" />
<input type="radio" class="foobar" id="x2" />
<input type="radio" class="foobar" id="x3" />

Clicking on the radios shows the alert box with the radio's id. Did you really click on the box, not some surrounding text or label element?

Ferdinand Beyer
Yes, it clicked the radio buttons. But there seems to be an error in my html. Sucks that it's so difficult to inspect html, even with Firebug...
AquinasTub