samedi 23 décembre 2017

How do I give values[1] the value 0 to avoid getting NaN as result in Javascript?

I am trying to create a program that adds 6 input values between them, but If i don't give a value (for example, if I give only 5 values) the result is NaN. So I tried to give the empty values the value of 0 using a for loop and an if statement, but It's not working. May I have your help please?

Code:

< script >

  document.getElementById("b").onclick = function() {

    var values = new Array();
    values[0] = document.getElementById("x").value;
    values[1] = document.getElementById("y").value;
    values[2] = document.getElementById("z").value;
    values[3] = document.getElementById("a").value;
    values[4] = document.getElementById("g").value;
    values[5] = document.getElementById("c").value;

    for (i = 0; i < values.length; i++) {
      if (isNaN(values[i])) {
        values[i] = 0;
      }
    }

    var risultato = parseFloat(values[0]) + parseFloat(values[1]) + parseFloat(values[2]) + parseFloat(values[3]) + parseFloat(values[4]) + parseFloat(values[5]);

    document.getElementById("risultato").innerHTML = "La massa del prodotto è " + risultato + ".";
  }
<form>
  <input type="number" placeholder="Valore 1" id="x" required>

  <input type="number" placeholder="Valore 2" id="y" required>

  <input type="number" placeholder="Valore 3 (se presente)" id="z">

  <input type="number" placeholder="Valore 4 (se presente)" id="a">

  <input type="number" placeholder="Valore 5 (se presente)" id="g">

  <input type="number" placeholder="Valore 6 (se presente)" id="c">

  <input type="button" class="btn btn-primary" id="b" value="Applica" />
</form>

<div id="risultato" class="desc"></div>

Aucun commentaire:

Enregistrer un commentaire