jQuery: Selecting by class and input type

Jquery

Jquery Problem Overview


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?

Jquery Solutions


Solution 1 - Jquery

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.

Solution 2 - Jquery

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

Solution 3 - Jquery

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.

Solution 4 - Jquery

You should use the class name like this

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

Try Using this a [live demo][1]

[1]: http://jsfiddle.net/mmzf2c2f/ "Live Demo"

Solution 5 - Jquery

Try this:

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

Solution 6 - Jquery

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

$(':button.myclass')

Solution 7 - Jquery

Another way:

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

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionBrian SullivanView Question on Stackoverflow
Solution 1 - JqueryPaolo BergantinoView Answer on Stackoverflow
Solution 2 - JqueryBaroqueBobcatView Answer on Stackoverflow
Solution 3 - JqueryeKek0View Answer on Stackoverflow
Solution 4 - JqueryAkhil ChandranView Answer on Stackoverflow
Solution 5 - JqueryFabio PaduaView Answer on Stackoverflow
Solution 6 - Jqueryiforce2dView Answer on Stackoverflow
Solution 7 - JqueryAnasSafiView Answer on Stackoverflow