Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

jQuery checkbox values to comma separated list

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?

like image 266
24creative Avatar asked Mar 06 '12 22:03

24creative


2 Answers

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(',');
like image 166
Selvakumar Arumugam Avatar answered Oct 20 '22 04:10

Selvakumar Arumugam


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(",");
like image 38
David Thomas Avatar answered Oct 20 '22 04:10

David Thomas