Ive been trying my hand in html.
Basically I just have to input field and want to add the two numbers together and display it in one of the input field.
The two inputs:
<input type="text" id="Num1" name="One"> <br>
<input type="text" id="Num2" name="Two"> <br>
Function for addition:
function calc(a, b) {
c = a + b;
document.getElementById("Num1").value = c;
}
Button click action:
<button onclick="calc(document.getElementsByName('One').value,
document.getElementsByName('Two').value);">
</button>
Output is "NaN", however if I used ElementById or ElementByName on function and button, nothing happens, if I put in defined numbers in calc() in the button part, I get the correct solution.
Full Code:
<!DOCTYPE html>
<html>
<head>
<title>The getElementById() Function</title>
<script>
function updateParagraphText(){
let labelElement = document.getElementById('label');
labelElement.innerText = 'You clicked the button!';
}
function calc(a, b) {
c = a + b;
document.getElementById("Num1").value = c;
}
</script>
</head>
<body>
<p id="label">
Click the button.
</p>
<button onclick="calc(document.getElementsByName('One').value, document.getElementsByName('Two').value);">
</button>
</body>
<form>
<input type="text" id="Num1" name="One"> <br>
<input type="text" id="Num2" name="Two"> <br>
</form>
</html>
3
Answers
If I’m not mistaken you’re having problems because
document.getElementsByName('One')
returns an array of elements (which contains only one element, yours).You should try
document.getElementsByName('One')[0].value
.Consider also casting the values to ints since those can be arbitrary strings by default.
See this working example: https://jsfiddle.net/wtpL2q80/9/
you can use
document.getElementById('Num1').value
instead ofdocument.getElementsByName('One').value
and useparseInt
to be able to sum them properlyYou need to use
getElementById
. The full code:I also corrected the values, because they were string instead of integers or float. Use
parseFloat
if it’s the case. I also added a third input to input the see the result, but you can use the second (Num2
) and remove the third.