![why](/static/img/x1mno0Ukhc-600.jpeg)
More then once you need to select all checked checkboxes in your web application. With JQuery this is a piece of cake. The following code returns all the checked checkbox values in an array AND in a string;
[javascript]
<script type="text/javascript">
function getchecked(){
// Get checked values
var selected = new Array();
$(‘input[type=checkbox]:checked’).each(function() {
selected.push($(this).val());
});
// convert to a string
var mystring = selected.join(",");
}
</script>
[/javascript]
In case you only need to get the checkboxes within a “div” you would something like this:
[javascript]
<script type="text/javascript">
function getchecked(){
// Get checked values
var selected = new Array();
$(‘#mydiv input:checked’).each(function() {
selected.push($(this).val());
});
// convert to a string
var mystring = selected.join(",");
}
</script>
[/javascript]
and in case you don’t need the values, but only the names you would use:
[javascript]
<script type="text/javascript">
function getchecked(){
// Get checked values
var selected = new Array();
$(‘input[type=checkbox]:checked’).each(function() {
selected.push($(this).attr(‘name’));
});
// convert to a string
var mystring = selected.join(",");
}
</script>
[/javascript]
Now, if you put this is a globally accessible function you will never have to revisit the code and it simply works in your project 🙂 Have fun.