Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

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

1 Answer

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...