getElementById or parseInt not working?

自闭症网瘾萝莉.ら 提交于 2019-12-13 01:19:52

问题


I am trying to write a simple form on HTML/Javascript where I type in a number, adds one and then displays it. I got it working but it was concatenating the one instead of adding it. I used the parseInt(), but it is showing "Nan". Any suggestions?

The HTML is:

<head> <link src="script.js" type="text/javascript"></script></head>
<body>
    <input type="text" id="grossSalary">
    <button type="button" onclick="calculateTax()"> 
    Generate Tax
    </button>
</body>

The Javascript is:

function calculateTax(){
   var salaryString = document.getElementById("grossSalary");
   var salaryInteger = parseInt(salaryString);
   alert(salaryInteger + 1);
}

The "error" message I get is:

"Nan"


回答1:


You forgot to extract value from input element:

var salaryString = document.getElementById("grossSalary").value;



回答2:


Add .value

 var salaryString = document.getElementById("grossSalary").value;



回答3:


You need to get the value, which is missed in your code.

var salaryString = document.getElementById("grossSalary").value;



回答4:


The problem is in your javascript where you set the salaryString variable. You need to make sure to collect the value of the element you are selecting. Like so:

var salaryString = document.getElementById("grossSalary").value;

After you do that, your code should behave as expected.




回答5:


The getElementById() method returns the element that has the ID attribute with the specified value. So when you try like

var salaryString = document.getElementById("grossSalary");

so here salaryString is a reference to an Element object, or null if an element with the specified ID is not in the document.

If you are looking fro get the value of the corresponding text box then use something like

var salaryString = document.getElementById("grossSalary").value;



回答6:


To find value from textbox you have to use .value. so update your JS code

function calculateTax(){
    var sal = document.getElementById("grossSalary");
    var salaryInteger = parseInt(sal.value);
    alert(salaryInteger + 1);
}


来源:https://stackoverflow.com/questions/28104061/getelementbyid-or-parseint-not-working

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!