New to website programming. I’m trying to make a basic sum equation with 2 input fields taken from client-side.
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form>
<input type="number" id="x">
<input type="number" id="y">
<script>
let x = document.getElementById('x').nodeValue;
let y = document.getElementById('y').nodeValue;
function sum(x, y) {
let sum = x + y;
alert(sum);
}
</script>
<input type="submit" value="submit" onclick="sum(x, y)">
</form>
</body>
</html>
I run my code in a browser(Opera Gx if that matters) and when I choose two numbers, then hit submit, it shows the alertbox. What shows up however is:
"[object HTMLInputElement][object HTMLInputElement]"
I know that the input elements are being used, but I obviously want my sum function to return a sum of the 2 input fields.
I don’t understand what I’m doing wrong.
3
Answers
The issue in your code is related to how you’re retrieving the values of the input fields. You’re using the
nodeValue
property, which is not the correct way to get the values of input elements. For whatnodeValue
returns check out docs.Instead, you should use the
value
property to retrieve the values of input elements. Here’s the corrected code:You should check the values of your inputs fields when the function is being called (and not once when the script is running like you have now, because you will get the wrong value).
To do so you can use the
.value
property instead of using thenodeValue
on the elements like this:This way
x
andy
are referring to the elements and you can extract the values when you want to.NOTICE – This will give you the wrong result, and this is because
.value
will return a string.You will also need to parse the values into numbers while summing:
You also don’t need to add parameters in your function