TlfT
TlfT

Reputation: 35

Simple JS function using text inputs and parseInt, returns NaN

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

Upvotes: 1

Views: 506

Answers (2)

sissonb
sissonb

Reputation: 3780

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

Upvotes: 0

Paul Rad
Paul Rad

Reputation: 4882

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 ;)

Upvotes: 1

Related Questions