Jquery set radio button checked, using id and class selectors

Alan A picture Alan A · Apr 11, 2013 · Viewed 194.6k times · Source

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.

Answer

nnnnnn picture nnnnnn · Apr 11, 2013

"...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.