Alessandro Lacava

on Designing and Developing Software. In love with Functional Programming.

How to Detect the Selected Checkboxes Using JavaScript

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

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
<html>
<head>
<script>
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>

<body>
<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.

Comments