Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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/

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading