开发者

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开发者_JAVA百科('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>


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.


The input fields contain strings. If you want to sum two numbers, you have to convert the strings to numbers before adding - otherwise you are just adding two strings. There are lots of ways to do that depending upon what you want to allow. Here's one:

   var x, y , result;
   x = Number(document.getElementById('value1').value);
   y = Number(document.getElementById('value2').value);
   result=x+y;
   alert(result);
   document.getElementById('res').value = result;

See it working here: http://jsfiddle.net/jfriend00/BWW2R/


document.getElementById('').value returns a string. You need to call parseInt on that to make it a number.


It's because x and y are actually strings, not numbers. The value field of the element is always a string, so x+y gives you the concatenation of x and y.

You can parse x and y as integers and add the result of the parsing: that will give you what you want.


The problem is when you take those values you are getting a string and in result you are doing a concatenation. You should use parseInt on both x and y like this:

x = parseInt(document.getElementById('value1').value);
y = parseInt(document.getElementById('value2').value);
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜