How to get many values selected of checkbox using Jquery
Dung Do Tien
Apr 10 2020
507
I have a form and this form content a list checks to get some favorite of the user but I don't know how to get all checkbox checked.
<div class="col-md-12 form">
<div class="title">Hobbies</div>
<div class="form-item">
<input type="checkbox" name="hobbies" id="checkbox-1" value="1" class="custom" />
<label for="checkbox-1">Films</label>
<input type="checkbox" name="hobbies" id="checkbox-2" value="2" class="custom" />
<label for="checkbox-2">Travle</label>
<input type="checkbox" name="hobbies" id="checkbox-3" value="3" class="custom" />
<label for="checkbox-3">Restaurant</label>
<input type="checkbox" name="hobbies" id="checkbox-4" value="4" class="custom" />
<label for="checkbox-4">Other</label>
</div>
</div>
I don't know how to select a checkbox group by its name.
How can I do this?
Have 1 answer(s) found.
-
S1
Sandeep Kumar Apr 12 2020
1. To check the status of a single checkbox you can use :checked selector as bellow:
$('#' + id).is(":checked")
2. To get the array value of checkboxes selected with the same name:
var checkbox = $('.form .form-item input[name=hobbies]:checked'); // return list checkbox object selected
And then you can loop through them and see what's checked you can do:
checkbox.each(function(){ // Do stuff here with this });
3. To validate form you can check the length of checkbox variable
if(checkbox == null || checkbox.length <= 0){ // show msg error here }
See demo code
* Type maximum 2000 characters.
* All comments have to wait approved before display.
* Please polite comment and respect questions and answers of others.