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.
>Solution :
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 what nodeValue returns check out docs.
Instead, you should use the value property to retrieve the values of input elements. Here’s the corrected code:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Sum Calculator</title>
</head>
<body>
<form>
<input type="number" id="x">
<input type="number" id="y">
<input type="submit" value="Submit" onclick="sum()">
</form>
<script>
function sum() {
// Retrieve the values of the input fields and try to parse them
let x = parseFloat(document.getElementById('x').value);
let y = parseFloat(document.getElementById('y').value);
// Check if the input values are valid numbers
if (!isNaN(x) && !isNaN(y)) {
// Perform the sum
let result = x + y;
alert("The sum is: " + result);
} else {
alert("Please enter valid numbers in both fields.");
}
}
</script>
</body>
</html>