1

I have some 20 check boxes ( dynamic number) in a HTML page which is checked by default. A user can uncheck it or leave it checked. At the end, there is a button to submit.

How to get the items that are only checked at the time of submitting?

qwww
  • 1,313
  • 4
  • 22
  • 48

2 Answers2

2

For a plain javascript solution, you can use document.querySelectorAll().

Retrieve the checkboxes and then loop over them, then push() all of the ones that have the checked: true property to an array called checked.

var checkboxes = document.querySelectorAll("input[type=checkbox]");
var submit = document.getElementById("submit");

function getChecked() {
  var checked = [];

  for (var i = 0; i < checkboxes.length; i++) {
    var checkbox = checkboxes[i];
    if (checkbox.checked) checked.push(checkbox.value);
  }

  return checked;
}

submit.addEventListener("click", function() {
  var checked = getChecked();
  console.log(checked);
});
<input type="checkbox" value="first" checked>
<input type="checkbox" value="second" checked>
<input type="checkbox" value="third" checked>

<input type="submit" id="submit">
Sam Holmes
  • 1,594
  • 13
  • 31
0

Get all check boxes by css Class and iterate to checked the condition element.checked on it

Check this code snippet

function checkCheckBoxes(){
$("input.abc").each(function(index, element){
  if(!element.checked){
   console.log(index+" not checked");
  } else{
  console.log(index+" checked");
  }
});
return false;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<form action="">
<input type="checkbox"  class="abc"/>
<input type="checkbox"  class="abc"/>
<input type="checkbox"  class="abc"/>
<input type="checkbox"  class="abc"/>
<input type="checkbox"  class="abc"/>
<input type="checkbox"  class="abc"/>
<input type="checkbox"  class="abc"/>
<input type="checkbox"  class="abc"/>
  <input type="submit"  onclick="return checkCheckBoxes()" value="Submit">
</form>
NullPointer
  • 7,094
  • 5
  • 27
  • 41