If a checkbox is marked or checked, it indicates to true, so first check one by one it’s true or not and then get all checked checkbox values in JavaScript.
A checkbox is allowing multiple selections at once, that’s why you can need to get them all selected values.
Example of getting all checked checkbox values in JavaScript
Let’s see simple HTML example code to get all checkbox values marked by the user.
<html>
<body>
<h4> Select the programming languages</h4>
<tr>
<td> Java: <input type="checkbox" id="check1" value="Java"> </td>
<td> PHP: <input type="checkbox" id="check2" value="PHP"> </td>
</tr> <tr>
<td> Python: <input type="checkbox" id="check3" value="Python"> </td>
<td> Android: <input type="checkbox" id="check4" value="Android"> </td>
<button onclick="getCheckboxValue()">Get slected values</button> <br>
<h4 style="color:green" id="result"></h4>
<script>
function getCheckboxValue() {
var l1 = document.getElementById("check1");
var l2 = document.getElementById("check2");
var l3 = document.getElementById("check3");
var l4 = document.getElementById("check4");
var res=" ";
if (l1.checked == true){
var pl1 = document.getElementById("check1").value;
res = res + pl1;
}
if (l2.checked == true){
var pl2 = document.getElementById("check2").value;
res = res + " " + pl2;
}
if (l3.checked == true){
var pl3 = document.getElementById("check3").value;
res = res + " " + pl3;
}
if (l4.checked == true){
var pl4 = document.getElementById("check4").value;
res = res+ " " + pl4;
}
alert(res);
}
</script>
</body>
</html>
Output:
Do comment if you have any doubts and suggestions on this tutorial.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version