1

I have this form with some dynamic fields called num_entradas.

If you add some numeric values onchange calculates the sum of all the fields with the function sumarTotalEntradas():

All of these works fine, but the problem is when I submit the form to a PHP page I only get the last field value. If I change the name attribute of the fields to num_entradas[] the submit is ok but then the sumaTotalEntradas() function doesn't work and totalEntradas fields remains in 0.

function sumarTotalEntradas() {
  var arr = document.getElementsByName('num_entradas');
  var tot = 0;
  var subtotal = 0;
  for (var i = 0; i < arr.length; i++) { 
    if (parseInt(arr[i].value))
      tot = tot + subtotal;
  }
  document.getElementById('totalEntradas').value = tot;

}
<form>
  <input type="number" min="0" step="1" maxlength="2" name="num_entradas" id="num_entradas" value="0" onchange="sumarTotalEntradas()">
  <input type="number" min="0" step="1" maxlength="2" name="num_entradas" id="num_entradas" value="0" onchange="sumarTotalEntradas()">
  <input type="number" min="0" step="1" maxlength="2" name="num_entradas" id="num_entradas" value="0" onchange="sumarTotalEntradas()">
  Total: <input type="text" maxlength="2" name="totalEntradas" id="totalEntradas" value="0"> €
</form>
mplungjan
  • 169,008
  • 28
  • 173
  • 236
damargon
  • 41
  • 3
  • Ids should be unique. It's not valid to have more than 1 element with the same id on your page. – Natrium Feb 12 '20 at 12:36
  • The field names should be sent to php as an array i.e. name="num_entradas[]". –  Feb 12 '20 at 12:37
  • 1
    @Natrium he is not using the IDs at all. It is not the problem here. It is still not valid though – mplungjan Feb 12 '20 at 12:40
  • Jeff, as I said if I change the name attribute to num_entradas[] the javascript function doesnt work. – damargon Feb 12 '20 at 12:41
  • ALso your code is wrong,. I removed the trailing 2 from sumar... and you need to do `var val = arr[i].value; if (!isNaN(val) && val !=="") tot += parseInt(val);` – mplungjan Feb 12 '20 at 12:45
  • You can get the number fields using `document.querySelectorAll("[name^=num_entradas]")` if you do not want to bother with the [] – mplungjan Feb 12 '20 at 12:48

0 Answers0