Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jquery set radio button checked, using id and class selectors

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.

like image 965
Alan A Avatar asked Apr 11 '13 12:04

Alan A


People also ask

How do you checked radio in jQuery?

We can check the status of a radio button by using the :checked jQuery selector together with the jQuery function is . For example: $('#el').is(':checked') . It is exactly the same method we use to check when a checkbox is checked using jQuery.


1 Answers

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

like image 97
nnnnnn Avatar answered Sep 20 '22 01:09

nnnnnn