Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

use jQuery to get values of selected checkboxes

I want to loop through the checkboxgroup 'locationthemes' and build a string with all selected values. So when checkbox 2 and 4 are selected the result would be: "3,8"

<input type="checkbox" name="locationthemes" id="checkbox-1" value="2" class="custom" /> <label for="checkbox-1">Castle</label> <input type="checkbox" name="locationthemes" id="checkbox-2" value="3" class="custom" /> <label for="checkbox-2">Barn</label> <input type="checkbox" name="locationthemes" id="checkbox-3" value="5" class="custom" /> <label for="checkbox-3">Restaurant</label> <input type="checkbox" name="locationthemes" id="checkbox-4" value="8" class="custom" /> <label for="checkbox-4">Bar</label> 

I checked here: http://api.jquery.com/checked-selector/ but there's no example how to select a checkboxgroup by its name.

How can I do this?

like image 689
Adam Avatar asked Jul 02 '12 11:07

Adam


People also ask

How can we get the value of selected checkboxes in a group using jQuery?

If you want to get checked checkboxes from a particular checkbox group, depending on your choice which button you have clicked, you can use $('input[name=”hobbies”]:checked') or $('input[name=”country”]:checked'). This will sure that the checked checkboxes from only the hobbies or country checkbox group are selected.

How can get multiple checkbox values from table in jQuery?

Using jQuery, we first set an onclick event on the button after the document is loaded. In the onclick event, we created a function in which we first declared an array named arr. After that, we used a query selector to select all the selected checkboxes. Finally, we print all the vales in an alert box.


1 Answers

In jQuery just use an attribute selector like

$('input[name="locationthemes"]:checked'); 

to select all checked inputs with name "locationthemes"

console.log($('input[name="locationthemes"]:checked').serialize());  //or  $('input[name="locationthemes"]:checked').each(function() {    console.log(this.value); }); 

Demo


In VanillaJS

[].forEach.call(document.querySelectorAll('input[name="locationthemes"]:checked'), function(cb) {    console.log(cb.value);  }); 

Demo


In ES6/spread operator

[...document.querySelectorAll('input[name="locationthemes"]:checked')]    .forEach((cb) => console.log(cb.value)); 

Demo

like image 149
Fabrizio Calderan Avatar answered Sep 17 '22 16:09

Fabrizio Calderan