109

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?

Fabrizio Calderan
  • 120,726
  • 26
  • 164
  • 177
Adam
  • 6,041
  • 36
  • 120
  • 208

12 Answers12

225

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

Fabrizio Calderan
  • 120,726
  • 26
  • 164
  • 177
41
$('input:checkbox[name=locationthemes]:checked').each(function() 
{
   // add $(this).val() to your array
});

Working Demo

OR

Use jQuery's is() function:

$('input:checkbox[name=locationthemes]').each(function() 
{    
    if($(this).is(':checked'))
      alert($(this).val());
});

Talha
  • 18,898
  • 8
  • 49
  • 66
25

Map the array is the quickest and cleanest.

var array = $.map($('input[name="locationthemes"]:checked'), function(c){return c.value; })

will return values as an array like:

array => [2,3]

assuming castle and barn were checked and the others were not.

Steffan Perry
  • 2,112
  • 1
  • 21
  • 21
19

$("#locationthemes").prop("checked")

usr4217
  • 420
  • 4
  • 18
14

Using jquery's map function

var checkboxValues = [];
$('input[name=checkboxName]:checked').map(function() {
            checkboxValues.push($(this).val());
});
MaylorTaylor
  • 4,671
  • 16
  • 47
  • 76
8

A bit more modern way to do it:

const selectedValues = $('input[name="locationthemes"]:checked').map( function () { 
        return $(this).val(); 
    })
    .get()
    .join(', ');

We first find all the selected checkboxes with the given name, and then jQuery's map() iterates through each of them, calling the callback on it to get the value, and returning the result as a new jQuery collection that now holds the checkbox values. We then call get() on it to get an array of values, and then join() to concatenate them into a single string - which is then assigned to the constant selectedValues.

ivanhoe
  • 4,593
  • 1
  • 23
  • 22
6
var SlectedList = new Array();
$("input.yorcheckboxclass:checked").each(function() {
     SlectedList.push($(this).val());
});
5
You can also use the below code
$("input:checkbox:checked").map(function()
{
return $(this).val();
}).get();
Tushar
  • 469
  • 1
  • 7
  • 14
3

So all in one line:

var checkedItemsAsString = $('[id*="checkbox"]:checked').map(function() { return $(this).val().toString(); } ).get().join(",");

..a note about the selector [id*="checkbox"] , it will grab any item with the string "checkbox" in it. A bit clumsy here, but really good if you are trying to pull the selected values out of something like a .NET CheckBoxList. In that case "checkbox" would be the name that you gave the CheckBoxList control.

mike
  • 2,149
  • 20
  • 29
2

Source - More Detail

Get Selected Checkboxes Value Using jQuery

Then we write jQuery script to get selected checkbox value in an array using jQuery each(). Using this jQuery function it runs a loop to get the checked value and put it into an array.

<!DOCTYPE html>
    <html lang="en">
    <head>
    <meta charset="utf-8">
    <title>Get Selected Checkboxes Value Using jQuery</title>
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <script type="text/javascript">
        $(document).ready(function() {
            $(".btn").click(function() {
                var locationthemes = [];
                $.each($("input[name='locationthemes']:checked"), function() {
                    locationthemes.push($(this).val());
                });
                alert("My location themes colors are: " + locationthemes.join(", "));
            });
        });
    </script>
    </head>
    <body>
        <form method="POST">
        <h3>Select your location themes:</h3>
        <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>
        <br>
        <button type="button" class="btn">Get Values</button>
    </form>
    </body>
    </html>
thecodedeveloper.com
  • 3,220
  • 5
  • 36
  • 67
2

Jquery 3.3.1 , getting values for all checked check boxes on button click

$(document).ready(function(){
 $(".btn-submit").click(function(){
  $('.cbCheck:checkbox:checked').each(function(){
 alert($(this).val())
  });
 });   
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" id="vehicle1" name="vehicle1"  class="cbCheck" value="Bike">
  <label for="vehicle1"> I have a bike</label><br>
  <input type="checkbox" id="vehicle2" name="vehicle2"  class="cbCheck" value="Car">
  <label for="vehicle2"> I have a car</label><br>
  <input type="checkbox" id="vehicle3" name="vehicle3"  class="cbCheck" value="Boat">
  <label for="vehicle3"> I have a boat</label><br><br>
  <input type="submit" value="Submit" class="btn-submit">
Bhanu Pratap
  • 1,635
  • 17
  • 17
1
var voyageId = new Array(); 
$("input[name='voyageId[]']:checked:enabled").each(function () {
   voyageId.push($(this).val());
});      
Saeed
  • 5,413
  • 3
  • 26
  • 40
Anmol Mourya
  • 530
  • 5
  • 7
  • A upgrade: `var voyageIds = $('input[name="voyageId[]"]:checked:enabled').map(function() {return this.value; }).get();` – William May 22 '20 at 00:15