Harry Potter
Harry Potter

Reputation: 15

equation from input field

I have three inputs which I want to add, When I place my first digit "5" console.log shows "0" the next input field I enter "2" this will console.log the first input field's digit "5" the third I enter "5" I see in console.log "7".

Why is this happening and how do I fix it please.

            <input id="roundOne" onkeypress="obtainScoreOne()" type="text">                
            <input id="roundTwo" onkeypress="obtainScoreOne()" type="text">                
            <input id="roundThree" onkeypress="obtainScoreOne()" type="text">

JavaScript.

             function mathScore(x, y, z){
                   return (x + y + z);
             }
             function obtainScoreOne() {    
                 //collect data
                 let n1, n2, n3, sum;
                    n1 = Number(document.querySelector('#roundOne').value);
                    n2 = Number(document.querySelector('#roundTwo').value);
                    n3 = Number(document.querySelector('#roundThree').value);        
                    sum = mathScore(n1, n2, n3);        
                 //Display result
                    console.log(sum);                     
              }

Upvotes: 0

Views: 249

Answers (2)

sonEtLumiere
sonEtLumiere

Reputation: 4572

I hope this helps

function obtainScoreOne(n1, n2, n3) {
  var n1 = parseInt(document.querySelector('#roundOne').value);
  var n2 = parseInt(document.querySelector('#roundTwo').value);
  var n3 = parseInt(document.querySelector('#roundThree').value);

  var sum;
  sum = n1 + n2 + n3;
  console.log(sum);
  return sum;                                          
}
<input id="roundOne" onkeyup="obtainScoreOne()" type="number" value="0">            
<input id="roundTwo" onkeyup="obtainScoreOne()" type="number" value="0">          
<input id="roundThree" onkeyup="obtainScoreOne()" type="number" value="0">

Upvotes: 1

SLePort
SLePort

Reputation: 15471

onkeypress is fired before the input value is set, try onkeyup instead:

function mathScore(x, y, z) {
  return (x + y + z);
}

function obtainScoreOne() {
  //collect data
  let n1, n2, n3, sum;
  n1 = Number(document.querySelector('#roundOne').value);
  n2 = Number(document.querySelector('#roundTwo').value);
  n3 = Number(document.querySelector('#roundThree').value);
  sum = mathScore(n1, n2, n3);
  //Display result
  console.log(sum);
}
<input id="roundOne" onkeyup="obtainScoreOne()" type="text">
<input id="roundTwo" onkeyup="obtainScoreOne()" type="text">
<input id="roundThree" onkeyup="obtainScoreOne()" type="text">

Upvotes: 0

Related Questions