$('input[type=checkbox]') All checkboxes will be selected, I mean, both checked and unchecked. Remember, this returns an array of elements, so you need to use each() jQuery function if you want to do something with them like printing their value.
We can use :checked selector in jQuery to select only selected values. In the above code, we created a group of checkboxes and a button to trigger the function. Using jQuery, we first set an onclick event on the button after the document is loaded.
$('.theClass:checkbox:checked')
will give you all the checked checkboxes with the class theClass
.
$('input:checkbox.class').each(function () {
var sThisVal = (this.checked ? $(this).val() : "");
});
An example to demonstrate.
:checkbox
is a selector for checkboxes (in fact, you could omit the input
part of the selector, although I found niche cases where you would get strange results doing this in earlier versions of the library. I'm sure they are fixed in later versions).
.class
is the selector for element class attribute containing class
.
Obligatory .map
example:
var checkedVals = $('.theClass:checkbox:checked').map(function() {
return this.value;
}).get();
alert(checkedVals.join(","));
$('input.yourClass:checkbox:checked').each(function () {
var sThisVal = $(this).val();
});
This would get all checkboxes of the class name "yourClass". I like this example since it uses the jQuery selector checked instead of doing a conditional check. Personally I would also use an array to store the value, then use them as needed, like:
var arr = [];
$('input.yourClass:checkbox:checked').each(function () {
arr.push($(this).val());
});
If you need to get the value of all checked checkboxes as an array:
let myArray = (function() {
let a = [];
$(".checkboxes:checked").each(function() {
a.push(this.value);
});
return a;
})()
$('input.theclass[type=checkbox]').each(function () {
var sThisVal = (this.checked ? $(this).val() : "");
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With