Brian Sullivan
Brian Sullivan

Reputation: 28563

jQuery: Selecting by class and input type

I would like to select a set of elements that are both of a certain input type (say, a checkbox) and have a certain class using jQuery. However, when I try the following:

 $("input:checkbox .myClass")

I don't get any items returned. How can I accomplish this in jQuery?

Upvotes: 140

Views: 319387

Answers (7)

AnasSafi
AnasSafi

Reputation: 6254

Another way:

$("input[class*='myClass']")

Upvotes: 1

iforce2d
iforce2d

Reputation: 8262

Just in case any dummies like me tried the suggestions here with a button and found nothing worked, you probably want this:

$(':button.myclass')

Upvotes: 3

Fabio Padua
Fabio Padua

Reputation: 31

Try this:

$("input:checkbox").hasClass("myClass");

Upvotes: 3

Akhil Chandran
Akhil Chandran

Reputation: 123

You should use the class name like this

$(document).ready(function(){
    $('input.addCheck').prop('checked',true);
});

Try Using this a live demo

Upvotes: 6

eKek0
eKek0

Reputation: 23289

You have to use (for checkboxes) :checkbox and the .name attribute to select by class.

For example:

$("input.aclass:checkbox")

The :checkbox selector:

Matches all input elements of type checkbox. Using this psuedo-selector like $(':checkbox') is equivalent to $('*:checkbox') which is a slow selector. It's recommended to do $('input:checkbox').

You should read jQuery documentation to know about selectors.

Upvotes: 7

Paolo Bergantino
Paolo Bergantino

Reputation: 488394

Your selector is looking for any descendants of a checkbox element that have a class of .myClass.

Try this instead:

$("input.myClass:checkbox")

Check it out in action.

I also tested this:

$("input:checkbox.myClass")

And it will also work properly. In my humble opinion this syntax really looks rather ugly, as most of the time I expect : style selectors to come last. As I said, though, either one will work.

Upvotes: 238

BaroqueBobcat
BaroqueBobcat

Reputation: 10150

If you want to get the inputs of that type with that class use:

$("input.myClass[type=checkbox]")

the [] selector syntax allows you to check against any of the elements attributes. Check out the spec for more details

Upvotes: 62

Related Questions