Not sure if this is a bug in jQuery 1.4.2 – I can’t figure out why this won’t work.
I need to check a radio button. I’m using attr({'checked':'checked'}), I also tried attr('checked':true) – none will work. But if I do attr('title':'whatever') on the same radio button, with no other change anyhwere, that DOES work everytime.
Is there some obscure difference between the title attribute and the checked attribute that I’m missing? They are both your everyday HTML attributes. So why does one work and the other one doesn’t?
Here’s the code:
$('.formradiodiv').live('click', function() {
//remove checked radio btns
$('input', $(this).parents('#radiogroup')).each(function() {
$(this).removeAttr('checked');
});
$('input', $(this)).attr('checked', true);
});
Edit: Alright, I believe I got it. Apparently it worked all along, and it was just my head temporarily being in tukka tukka land or something.
I was checking the source code to see if jQuery had added the “checked” attr to the radio button I was clicking on: in Firefox, highlight content, right click > View Selection Source. Doing this usually shows all changes to the DOM done by JavaScript, and I was expecting to see the attribute in the source code.
All this time, the HTML radio button was hidden via CSS. That’s the reason I need this in the first place – I’m replacing the default radio button with an image.
So in the source code, I didn’t see the checked attribute on the radio button, hence I assumed that it was jQuery not working correctly. But as soon as I removed the CSS rule, and showed the buttons for testing, I saw that they actually do get checked correctly. Nuff said.
Thank you very much to all who commented. I’ll vote y’all up.
Cheers
Jab in the dark: I suspect that
$('input', $(this))matches other types of<input>elements besides check boxes, and that something goes wrong when setting thecheckedattribute of those elements.Try to restrict your selector to check boxes only (also note you don’t need to wrap
thiswhen using it as a selector context):