Suood -
Suood -

Reputation: 3

One output from multiple inputs in javascript

<!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

Answers (1)

palaѕн
palaѕн

Reputation: 73906

Few issues here:

  • You need to use 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
  • Next, you have typo in getElementsById. It is getElementById as it only get one element with the specified ID, not multiples.
  • Also, if you only need to display text content inside the output span, then you can simply use textContent instead, as shown in the demo.

Using textContent:

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>

Using innerHTML:

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

Related Questions