Jquery set radio button checked, using id and class selectors
Asked Answered
O

1

59

Is it possible to set a radio button to checked using jquery - by a class and an id?

For example:

$('input:radio[class=test1 id=test2]).attr('checked', true);

I only seem to be able to set it by id OR class but not by both.

Omegaomelet answered 11/4, 2013 at 12:54 Comment(0)
S
137

"...by a class and a div."

I assume when you say "div" you mean "id"? Try this:

$('#test2.test1').prop('checked', true);

No need to muck about with your [attributename=value] style selectors because id has its own format as does class, and they're easily combined although given that id is supposed to be unique it should be enough on its own unless your meaning is "select that element only if it currently has the specified class".

Or more generally to select an input where you want to specify a multiple attribute selector:

$('input:radio[class=test1][id=test2]').prop('checked', true);

That is, list each attribute with its own square brackets.

Note that unless you have a pretty old version of jQuery you should use .prop() rather than .attr() for this purpose.

Sherer answered 11/4, 2013 at 12:55 Comment(1)
Thanks I managed to get it working with: $('#test2.test1).prop('checked', true); - I think that I tried this approach but had the class before the ID. Yes - I did mean ID when I said DIv.Omegaomelet

© 2022 - 2024 — McMap. All rights reserved.