Alex Williams
Alex Williams

Reputation: 99

Text Value From HTML Into Javascript Var?

I would like to know if the following line is the correct way to take html and put it into a Javascript var as numeric value?

var thePoolHeatingFeeRounded = Number(document.getElementsById("priceDisplayPoolHeating").innerHTML);

Nevermind that the variable name has the word 'rounded' in it. The value that I am trying to put into this var is a 2 point float that has already been rounded and it exist as html.

Below is the line of HTML code that is referenced by getElementsById...

$<div id="priceDisplayPoolHeating" class="priceDisplay">8.00</div>

Any input is greatly appreciated.

Upvotes: 0

Views: 76

Answers (2)

Ian Hazzard
Ian Hazzard

Reputation: 7771

You are very close. Supposed to be getElementById, not Elements. I created a little code to show you how it works.

Here's what the code looks like in this website's code displayer:

function displayText(){

var thePoolHeatingFeeRounded = Number(document.getElementById("priceDisplayPoolHeating").innerHTML)

  alert(thePoolHeatingFeeRounded);
}
<div id="priceDisplayPoolHeating">8.01</div><input type="button" onclick="displayText()" value="Display the innerHTML of Pool Heating">

Upvotes: 1

nothingisnecessary
nothingisnecessary

Reputation: 6223

Try this instead:

var thePoolHeatingFeeRounded = Number(document.getElementById("priceDisplayPoolHeating").innerHTML);

You were calling getElementsById which is not correct (it is not plural), I changed it to getElementById

Tip: if you need to check whether the Number is valid you can use !isNaN(thePoolHeatingFeeRounded) or use a trick to turn it into a default number (such as 0 or -1) like this:

var thePoolHeatingFeeRounded = Number(document.getElementById("priceDisplayPoolHeating").innerHTML) || 0;

You can also use parseFloat():

var thePoolHeatingFeeRounded = parseFloat(document.getElementById("priceDisplayPoolHeating").innerHTML) || 0;

Upvotes: 3

Related Questions