20

I have several checkboxes with a name array and I want the output of the checked boxes to be a variable with a comma separated list.

<input type="checkbox" name="example[]" value="288" />
<input type="checkbox" name="example[]" value="289" />
<input type="checkbox" name="example[]" value="290" />

For example if the first and last box are selected the output will be:

var output = "288,290";

How can I do this with jQuery?

VLAZ
  • 26,331
  • 9
  • 49
  • 67
24creative
  • 709
  • 2
  • 9
  • 14
  • possible duplicate of [jQuery Array of all selected checkboxes (by class)](http://stackoverflow.com/questions/2099164/jquery-array-of-all-selected-checkboxes-by-class) – Felix Kling Mar 06 '12 at 22:56

3 Answers3

35

You can use :checkbox and name attribute selector (:checkbox[name=example\\[\\]]) to get the list of checkbox with name="example[]" and then you can use :checked filter to get only the selected checkbox.

Then you can use .map function to create an array out of the selected checkbox.

DEMO

var output = $.map($(':checkbox[name=example\\[\\]]:checked'), function(n, i){
      return n.value;
}).join(',');
Selvakumar Arumugam
  • 79,297
  • 15
  • 120
  • 134
  • Hmmm, this seems to return a list of all (checked) checkboxes even with those without the name of example[]. e.g. http://jsfiddle.net/6LCvN/ . Any idea why? – Hugh Apr 10 '13 at 03:40
  • @Hugh Missed it somehow, but you need double slashes to escape the `[` and `]` http://jsfiddle.net/6LCvN/22/ or wrap in quotes http://jsfiddle.net/hmtdtwbr/ – Selvakumar Arumugam Nov 25 '14 at 20:47
12

Currently un-tested, but I believe the following should work:

var valuesArray = $('input:checkbox:checked').map( function () {
    return $(this).val();
}).get().join();

Edited, after a small break, to use native DOM, rather than $(this).val() (which is needlessly expensive, in context):

var valuesArray = $('input:checkbox:checked').map( function() {
    return this.value;
}).get().join(",");
Subedi Kishor
  • 5,906
  • 5
  • 35
  • 53
David Thomas
  • 249,100
  • 51
  • 377
  • 410
4
var valuesArray = $('input[name="valuehere"]:checked').map(function () {  
        return this.value;
        }).get().join(",");

works for me always

Faisal
  • 190
  • 1
  • 11