Search code examples
javascripthtmlcalculator

Problems with simple calculator using html


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>

Solution

  • 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/