简体   繁体   中英

javascript document.getElementById().value

Sorry, I'm newbie,

<html>
<head>
<script type="text/javascript">
var x = document.getElementById('x').value;
var y = document.getElementById('y').value;
var z = x + y;
alert(z);
</script>
</head>

<body>
<input type="number" id="x" />
<input type="number" id="y" />
</body>

</html>

If my input x = 100, and y input = 200. My popup alert are 100200.

How to fixed this?

thank you.

It's because the value is a string , you need to convert it to a number and then do the addition.. This should do it..

<html>
<head>
<script type="text/javascript">
    var x = parseInt(document.getElementById('x').value);
    var y = parseInt(document.getElementById('y').value);
    var z = x + y;
    alert(z);
</script>
</head>

<body>
    <input type="number" id="x" />
    <input type="number" id="y" />
</body>

</html>

Function parseInt will convert the string to an integer number and then 100+200 will be 300.

Find the Fiddle here

Use

var z = parseInt(x) + parseInt(y);

You need to typecast variables using parseInt(var) since they are strings.

<html>

<head>
    <script type="text/javascript">
    var x = document.getElementById('x').value;
    var y = document.getElementById('y').value;
    var z = parseInt(x) + pasreInt(y);
    alert(z);
    </script>
</head>

<body>
    <input type="number" id="x" />
    <input type="number" id="y" />
</body>

</html>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM