Javascript Form How to - Get checked checkbox








Question

We would like to know how to get checked checkbox.

Answer


<!DOCTYPE html>
<html>
<head>
</head><!--from w w w.  j a  v  a2s.com-->
<body>
  <div style="width: 100%">
    <input type="checkbox" id="cb1">
  </div>
  <div style="width: 100%">
    <input type="checkbox" id="cb2">
  </div>
  <div style="width: 100%">
    <input type="checkbox" id="cb3">
  </div>
  <div style="width: 100%">
    <input type="submit" id="execute" value="Execute" onClick="run();">
  </div>
  <div id="result"></div>
  <script type='text/javascript'>
function run() {
    myArr = ["2","You selected first checkbox", "You selected second checkbox", "You selected the last one"];
    snip = "<div>HERE GOES YOUR CHECKBOX CHOICE: </div>";
    for(m=1;m<4;m++) {
    if(document.getElementById("cb"+m).checked == true) {
      snip += "<br/> - " + myArr[m];
    }
  }
  document.getElementById('result').innerHTML = snip;
}

</script>
</body>
</html>

The code above is rendered as follows: