1

Can anyone help me figure out why I keep getting a NaN result?

   function showShares() {
 var tot = document.getElementById('total').innerHTML;
 var pri = document.getElementById('price').innerHTML;
 var per = document.getElementById('percent').innerHTML;

 var shar = parseInt(tot, 10) * parseFloat(per) / parseFloat(pri);
   document.getElementById("shares").innerHTML=Math.round(shar);

}

<td><text id="price"><%= StockQuote::Stock.quote(current_user.fund1).last %></text></td>

 <td><text id="shares"></text></td>
 <td><text id="percent">.50</text></td>

<p class="alignright1"><input type="text" id="total" size="8"></input>
<br><a href onclick="showShares()">here</a>


The stock quote is returning an integer in the cell ie. 25.38. it returns the same NaN if I remove the embedded ruby and place a simple integer ie. 50. The same is true if I replace the input with a number.

Thank You

4
  • Debug, e.g. alert( parseInt(tot, 10) + ' | '+ parseInt(per, 10) +' | '+parseInt(pri, 10) ) Commented Sep 28, 2013 at 0:02
  • NaN | NaN | 23 .. Thats Cool! Commented Sep 28, 2013 at 0:11
  • document.getElementById('total').innerHTML isn't the way to get a value from an input element. Try document.getElementById('total').value Commented Sep 28, 2013 at 0:14
  • Thank You Very Much! I was using .value earlier. The debug code was very Helpful! Commented Sep 28, 2013 at 0:18

2 Answers 2

1

Try this :

function showShares() {
 var tot = document.getElementById('total').innerHTML;
 var pri = document.getElementById('price').innerHTML;
 var per = document.getElementById('percent').innerHTML;

 var shar = parseInt(tot, 10) * parseFloat(per, 10) / parseInt(pri, 10);
   document.getElementById("shares").innerHTML=Math.round(shar);

}

The percent value is a float (digit with comma) and must be interpreted by the JS engine like a float ;)

Sign up to request clarification or add additional context in comments.

1 Comment

Thank You, I had just realized this too. Combined with the debug help above I get NaN | .5 | 23
0

You are trying to get a value from an input element with this code, document.getElementById('total').innerHTML

That's not the way to get the value from the input. You should use this code,

document.getElementById('total').value

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.