最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

passing javascript variable to html for display - Stack Overflow

programmeradmin2浏览0评论

I am using the following

var loan = parseFloat(document.getElementById("loanamount"));

document.getElementById('numpay').textContent = loan.toString();

and my html is this:

<p>Number of Payments:    <a id="numpay"> </a> </p>

I feel like this should be working but cannot seem to get anything other than NaN in my html, no matter how I configure it. I know I am a novice at javascript but could you please give me a tip?

Thanks!

I am using the following

var loan = parseFloat(document.getElementById("loanamount"));

document.getElementById('numpay').textContent = loan.toString();

and my html is this:

<p>Number of Payments:    <a id="numpay"> </a> </p>

I feel like this should be working but cannot seem to get anything other than NaN in my html, no matter how I configure it. I know I am a novice at javascript but could you please give me a tip?

Thanks!

Share Improve this question asked Feb 1, 2013 at 17:50 ljrhljrh 4498 silver badges21 bronze badges 3
  • 3 what is the tag with id loanamount? – cha0site Commented Feb 1, 2013 at 17:51
  • 2 Why are you parsing a float and then stringifying it? – Evan Davis Commented Feb 1, 2013 at 17:55
  • just curious but I would imagine the value you're pulling back is a string as you are parsing it with parseFloat. Then in the next line you're calling .toString(). Seems a little counter productive. – War10ck Commented Feb 1, 2013 at 17:55
Add a ment  | 

5 Answers 5

Reset to default 3

You need parseFloat(document.getElementById("loanamount").value) most probably

TIP: Instead of parseFloat, just use + to convert from strings to numbers. So +document.getElementById("loanamount").value should also serve your purpose.

var loan = parseFloat(document.getElementById("loanamount").value);

document.getElementById('numpay').textContent = loan.toString();

If you aren't doing anything with loan then just do this:

document.getElementById('numpay').textContent = document.getElementById("loanamount").value

If the element with id loanamount is an input you will need .getElementById("loanamount").value, if it is a span or div then .getElementById("loanamount").innerHTML. For writing back the same apply.

But in either case you must not use .toString() on the write in. parseFloat() will give you a number, which does not have methods. JavaScript is not that similar to Java.

  var loan = parseFloat(document.getElementById("loanamount").value);

  document.getElementById('numpay').innerHTML = loan.toFixed(2);
发布评论

评论列表(0)

  1. 暂无评论