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.
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(",");
var valuesArray = $('input[name="valuehere"]:checked').map(function () { return this.value; }).get().join(",");
works for me always
jQuery how to get multiple checkbox's value and output as comma separated String list.
https://www.tutsmake.com/jquery-multiple-checkbox-values-to-comma-separated-string/
$(document).ready(function() {
$(".btn_click").click(function(){
var programming = $("input[name='programming']:checked").map(function() {
return this.value;
}).get().join(', ');
alert("My favourite programming languages are: " + programming);
});
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>jQuery Get Values of Selected Checboxes</title>
<script src="https://code.jquery.com/jquery-3.3.1.min.js"></script>
</head>
<body>
<form>
<h3>Select your favorite Programming Languages :</h3>
<label><input type="checkbox" value="PHP" name="programming"> PHP</label>
<label><input type="checkbox" value="Java" name="programming"> Java</label>
<label><input type="checkbox" value="Ruby" name="programming"> Ruby</label>
<label><input type="checkbox" value="Python" name="programming"> Python</label>
<label><input type="checkbox" value="JavaScript" name="programming"> JavaScript</label>
<label><input type="checkbox" value="Rust" name="programming">Rust</label>
<label><input type="checkbox" value="C" name="programming"> C</label>
<br>
<button type="button" class="btn_click" style="margin-top: 10px;">Click here to Get Values</button>
</form>
</body>
</html>
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(',');