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\"
You can also use the below code
$("input:checkbox:checked").map(function()
{
return $(this).val();
}).get();
$("#locationthemes").prop("checked")
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>
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
$('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());
});
var voyageId = new Array();
$("input[name='voyageId[]']:checked:enabled").each(function () {
voyageId.push($(this).val());
});