How to detect the selected checkboxes using JavaScript
Here is an example of how you can retrieve the selected checkboxes using a JavaScript function:
HTML:
-
function getSelectedValues(elem)
-
{
-
var elemNumber = document.myForm.test.length;
-
-
var selectedElems = [];
-
for(j = 0; j <elemNumber; j++)
-
{
-
if(elem[j].checked)
-
{
-
selectedElems.push(elem[j].value);
-
}
-
}
-
return selectedElems;
-
}
-
</script>
-
</head>
-
-
<form id="myForm" name="myForm">
-
<input type="checkbox" id="test" name="myCheckBox" value="test1">
-
Test 1
-
-
-
<input type="checkbox" id="test" name="myCheckBox" value="test2">
-
Test 2
-
-
-
<input type="button" value="Click Here" onclick="alert(getSelectedValues(document.myForm.myCheckBox));">
-
</form>
-
</body>
-
-
</html>
In the previous example when the user clicks on the button the selected checkboxes are displayed through an alert.