Sajeed Thajudeen Sajeed Thajudeen - 18 days ago 4
HTML Question

Required All Checked boxes to be display from one form to another with "," seperation

I have issue with to show All Checked boxes to be display from one form to another with "," separation.

Presently below script is working to show only one checked box

<html>

<body>
<form id="form1">
<input name="items[]" id="item1" type="checkbox" value="item1" checked>
<input name="items[]" id="item2" type="checkbox" value="item2">
<input name="items[]" id="item3" type="checkbox" value="item3">

<input type="button" border="2" onClick="checkedBox();" >
</form>

<form id="form2">

<p id="view" id="view">Display Here</p>


</form>
<script>

function checkedBox() {
var input = document.querySelector('input[name="items[]"]:checked').value;
document.getElementById("view").innerHTML = input;
}
</script>
</body>
</html>


Please assist me to display all checked boxes, ex: if item 1 and 2 selected, should view as "item1 , item2"

Answer

Use querySelectorAll instead of querySelector then loop through each element and get its value

try this :

function checkedBox() {
  document.getElementById("view").innerHTML = "";
  var input = document.querySelectorAll('input[name="items[]"]:checked');
  for (i = 0; i < input.length; i++) {
    document.getElementById("view").innerHTML += input[i].value;
    if(i!=(input.length-1)) {
      document.getElementById("view").innerHTML += ",";
    }
  }
}
<form id="form1">
  <input name="items[]" id="item1" type="checkbox" value="item1" checked>
  <input name="items[]" id="item2" type="checkbox" value="item2">
  <input name="items[]" id="item3" type="checkbox" value="item3">

  <input type="button" border="2" onClick="checkedBox();">
</form>

<form id="form2">

  <p id="view" id="view">Display Here</p>


</form>