Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
268 views
in Technique[技术] by (71.8m points)

javascript - Addition operation issues?

Hi i'm trying to do simple addition of two numbers in javascript. When i'm trying to get the two input element values, the result is coming in a concatenation of two numbers

Here is the code:

<html>
<title>
</title>
<head>
<script type="text/javascript">
function loggedUser() {
    //Get GUID of logged user
   //alert('success');
   var x, y , result;
   x = document.getElementById('value1').value;
   y = document.getElementById('value2').value;
   result=x+y;
   alert(result);
   document.getElementById('res').value = result;
}
</script>
</head>
<body>
<input type="text" id="value1"><br>
<input type="text" id="value2"><br>
<input type="text" id="res">
<input type="submit" value ="submit" onclick=loggedUser();>
</body>
</html>
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

The "+" operator is overloaded. If any of the parameters is a string, they are all converted to strings and concatenated. If the parameters are numbers, then addition is done. Form control values are always strings.

Convert the parameters to numbers first using one of the following:

x = Number(document.getElementById('value1').value);

or

x = parseInt(document.getElementById('value1').value, 10);

or

x = parsefloat(document.getElementById('value1').value);

or

x = +document.getElementById('value1').value;

or

x = document.getElementById('value1').value * 1;

and so on...

Oh, you can also convert it only when necessary:

result = Number(x) + Number(y);

etc.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...