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\"
Jquery 3.3.1 , getting values for all checked check boxes on button click
$(document).ready(function(){
$(".btn-submit").click(function(){
$('.cbCheck:checkbox:checked').each(function(){
alert($(this).val())
});
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="checkbox" id="vehicle1" name="vehicle1" class="cbCheck" value="Bike">
<label for="vehicle1"> I have a bike</label><br>
<input type="checkbox" id="vehicle2" name="vehicle2" class="cbCheck" value="Car">
<label for="vehicle2"> I have a car</label><br>
<input type="checkbox" id="vehicle3" name="vehicle3" class="cbCheck" value="Boat">
<label for="vehicle3"> I have a boat</label><br><br>
<input type="submit" value="Submit" class="btn-submit">
Map the array is the quickest and cleanest.
var array = $.map($('input[name="locationthemes"]:checked'), function(c){return c.value; })
will return values as an array like:
array => [2,3]
assuming castle and barn were checked and the others were not.
var SlectedList = new Array();
$("input.yorcheckboxclass:checked").each(function() {
SlectedList.push($(this).val());
});
Using jquery's map
function
var checkboxValues = [];
$('input[name=checkboxName]:checked').map(function() {
checkboxValues.push($(this).val());
});
So all in one line:
var checkedItemsAsString = $('[id*="checkbox"]:checked').map(function() { return $(this).val().toString(); } ).get().join(",");
..a note about the selector [id*="checkbox"]
, it will grab any item with the string "checkbox" in it. A bit clumsy here, but really good if you are trying to pull the selected values out of something like a .NET CheckBoxList. In that case "checkbox" would be the name that you gave the CheckBoxList control.
A bit more modern way to do it:
const selectedValues = $('input[name="locationthemes"]:checked').map( function () {
return $(this).val();
})
.get()
.join(', ');
We first find all the selected checkboxes with the given name, and then jQuery's map() iterates through each of them, calling the callback on it to get the value, and returning the result as a new jQuery collection that now holds the checkbox values. We then call get() on it to get an array of values, and then join() to concatenate them into a single string - which is then assigned to the constant selectedValues.