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!
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!
Share Improve this question edited Mar 26, 2009 at 13:31 AquinasTub asked Mar 26, 2009 at 12:23 AquinasTubAquinasTub 8,5856 gold badges24 silver badges15 bronze badges 3- It would be helpful to see your HTML. – tvanfosson Commented Mar 26, 2009 at 12:26
- "Does this.id really return the id of the current radio button?" yep – Konstantin Tarkus Commented Mar 26, 2009 at 12:36
- HTML: <input type='radio' name='thingy' class='foobar' value='foo' id='thingy' /> – AquinasTub Commented Mar 26, 2009 at 12:37
4 Answers
Reset to default 3$("input.foobar").change(function () {
alert(this.id);
});
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.
Try
$("input.foobar").change(function ()
rather than .click(function ()
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?