Pete Pete - 10 days ago 6
HTML Question

HTML checking for mutiple checkbox

I'm writing a piece of code as an exercice in HTML that allows the user to tick boxes (the code below is simplified, from 8 checkboxes to 2) and the text totalPrice should show the price of the item selected.

<script type='text/javascript'>
function f(){
if(document.form1.nano1Gb.checked == true)
document.form1.totalPrice.value = document.form1.priceNano1Gb.value
if(document.form1.nano4Gb.checked == true)
document.form1.totalPrice.value = document.form1.priceNano4Gb.value
if(document.form1.nano1Gb.checked == true && document.form1.nano4Gb.checked == true)
document.form1.totalPrice.value = parseInt(document.form1.priceNano1Gb.value) + parseInt(document.form1.priceNano4Gb.value)
}
</script>
<body>
<form name='form1'>
<p>
<input type='checkbox' name='nano1Gb' onclick=f(); />
<input type='text' value='Nano 1GB'>
<input type='text' name='priceNano1Gb' value='90'</p>

<p>
<input type='checkbox' name='nano4Gb' onclick=f(); />
<input type='text' value='Nano 4 GBb'>
<input type='text' name='priceNano4Gb' value='155'</p>

<p><input type='text' name="totalPrice" placeholder="Total Price"></p>


This works with two elements, but with 8 elements, it seems highly inefficient for me to great hundreds of conditions checking every single box and totaling what else has been checked. How can I code this better? Thanks!

Answer
  1. Give them a class.
  2. Use document.querySelectorAll(".yourclassname:checked")
  3. loop over result
  4. give total an ID and set the value

window.onload = function() {
  var checks = document.querySelectorAll(".chk");
  for (var i = 0; i < checks.length; i++) {
    checks[i].onclick = function() {
      total();
    }
  }
}

function getNext(next) {
  do next = next.nextSibling;
  while (next && next.nodeType !== 1);
  return next;
}

function total() {
  var total = 0;
  var checks = document.querySelectorAll(".chk:checked");
  for (var i = 0; i < checks.length; i++) {
    var nameField = getNext(checks[i]);
    var priceField = getNext(nameField);
    total += parseInt(priceField.value, 10);
  }
  document.querySelector("#total").value = total
}
<form name='form1'>
  <p>
    <input class="chk" type='checkbox' name='nano1Gb' />
    <input type='text' value='Nano 1GB'>
    <input type='text' name='priceNano1Gb' value='90' />
  </p>

  <p>
    <input class="chk" type='checkbox' name='nano4Gb' />
    <input type='text' value='Nano 4 GBb'>
    <input type='text' name='priceNano4Gb' value='155' />
  </p>

  <p>
    <input id="total" type='text' name="totalPrice" placeholder="Total Price">
  </p>
</form>