How to detect the selected checkboxes using JavaScript

Here is an example of how you can retrieve the selected checkboxes using a JavaScript function:

function getSelectedValues(elem) {
  var elemNumber = document.myForm.test.length;

  var selectedElems = [];
  for(j = 0; j < elemNumber; j++) {
    if(elem[j].checked) {
  return selectedElems;

<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" 


In the previous example when the user clicks on the button the selected checkboxes are displayed through an alert.

comments powered by Disqus