Reputation: 3
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title>JavaScript Multiple inputs</title>
</head>
<body>
<div class="">
<input type="number" max="5" min="1" name="input1" value="0" placeholder="0"><br>
<input type="number" max="5" min="1" name="input2" value="0" placeholder="0"><br>
<button type="button" name="button" onclick="calculate()">test</button><br>
<span id="output"> output is </span>
</div>
<script type="text/javascript">
function calculate() {
var input1 = getElementsByName('input1').value ;
var input2 = getElementsByName('input2').value ;
getElementsById('output').innerHTML = (2*input1) + (input2/2) ;
}
</script>
</body>
</html>
I want to make an output based on multiple outputs. In this script, I want to make some calculations of the inputs of the user. However, every time I try to run the code the output does not show any result (I am a beginner).
Upvotes: 0
Views: 1831
Reputation: 73906
Few issues here:
document
before all method name like getElementsByName
, etc.document.getElementsByName
get all elements with the specified name. So, it is actually returning an array. So, you will need to access the firslt element in the array's value using document.getElementsByName('input1')[0].value
getElementsById
. It is getElementById
as it only get one element with the specified ID, not multiples.output
span, then you can simply use textContent
instead, as shown in the demo.function calculate() {
var input1 = document.getElementsByName('input1')[0].value;
var input2 = document.getElementsByName('input2')[0].value;
document.getElementById('output').textContent = (2 * input1) + (input2 / 2);
}
<input type="number" max="5" min="1" name="input1" value="0" placeholder="0"><br>
<input type="number" max="5" min="1" name="input2" value="0" placeholder="0"><br>
<button type="button" name="button" onclick="calculate()">test</button><br>
<span id="output"> output is </span>
function calculate() {
var input1 = document.getElementsByName('input1')[0].value;
var input2 = document.getElementsByName('input2')[0].value;
document.getElementById('output').innerHTML =
`<div class='result'>${(2 * input1) + (input2 / 2)}</div>`;
}
.result {
padding: 20px;
margin: 10px;
border: 1px solid #777;
}
<input type="number" max="5" min="1" name="input1" value="0" placeholder="0"><br>
<input type="number" max="5" min="1" name="input2" value="0" placeholder="0"><br>
<button type="button" name="button" onclick="calculate()">test</button><br>
<span id="output"> output is </span>
For more info:
Upvotes: 3