How to Get all Selected Checkbox Values in Comma Separated String using jQuery

Generally, the selected checkbox values are returned in an array on HTML form submission. You can also get the checked checkbox values without form submission using jQuery. If you don’t want to use the server-side script to get the checkbox values, jQuery is an easy option to get the values from the selected checkboxes at the front-side script.

In this example code, we will show you how to get all the selected checkboxes values in comma-separated string using jQuery. Use the following code snipper to get selected checkbox values separated by comma in jQuery.

HTML checkbox fields with name array:

<input type="checkbox" name="product_id[]" value="123" />
<input type="checkbox" name="product_id[]" value="345" />
<input type="checkbox" name="product_id[]" value="678" />
<input type="checkbox" name="product_id[]" value="901" />

Get selected values using jQuery:

  • Select checkboxes using the name attribute selector (:checkbox) and filter the checked checkboxes using :checked attribute.
  • Use the jQuery map() function to create an array of the selected checkbox values, then use the join() method to convert array into a comma (,) separated string.
var product_ids_str = $.map($(':checkbox[name=product_id\\[\\]]:checked'), function(n, i){
    return n.value;
}).join(',');

Leave a reply

keyboard_double_arrow_up