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.
The issue in your code is related to how you're retrieving the values of the input fields. You're using the
nodeValueproperty, which is not the correct way to get the values of input elements. For whatnodeValuereturns check out docs.Instead, you should use the
valueproperty to retrieve the values of input elements. Here's the corrected code: