0

I know this must be very simple, but I'm having two issues with my simple JavaScript that I can't figure out. Please bear with any mistakes I'm making - I'm new to this process as well as StackOverflow.

I'm not sure how to add two values from inputs on an HTML page so that the answers are concatenated. My other issue is that when my answer is submitted, it only flashes for a brief moment and then disappears. What am I doing wrong to make this keep occurring? I appreciate any wisdom that you could impart.

<!DOCTYPE html>
<html>
  <head>
    <title>Doodle, 3-16-18</title>
  </head>
  <body>
    <h1>Calculator</h1>
    <form>
        <input id="one" type="number">First Number<br>
        <input id="two" type="number">Second Number<br>
        <button onclick="addNumbers()">Add</button>
    </form>
    <p id="answer"></p>
    <script>
        addNumbers() {
            var firstNumber = document.getElementById("one").value;
            var secondNumber = document.getElementById("two").value;
            var answer = firstNumber+ secondNumber;
            document.getElementById("answer").innerHTML = answer;
        }
    </script>
  </body>

  • 1
    Also, [Stop form refreshing page on submit](https://stackoverflow.com/questions/19454310/stop-form-refreshing-page-on-submit/19454378) (this is why the answer is disappearing) – Jonathan Lonowski Mar 17 '18 at 01:17
  • See [`parseFloat()`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseFloat) to solve your addition problem. See `form` `onSubmit` `event` [`preventDefault()`](https://developer.mozilla.org/en-US/docs/Web/API/Event/preventDefault) to solve your flashing issue. – Arman Charan Mar 17 '18 at 01:21
  • 1
    I would like to give you idea to debug JavaScript code. Use "debugger" keywords in you code. Just write "debugger;" after "addNumber(){" then open your open your browser then right click on browser and select "inspect" ,Now click on add button and then run your code step by step. You will come to know where is wrong. Or find in Google how to use " debugger" in JavaScript. It will make your life easy in JavaScript. – Raju Mar 17 '18 at 02:11
  • Thank you for your help, everyone! I figured out three issues thanks to your advice. Here's what was happening: silly old me forgot to declare addNumbers() as a function, the button needed a type attribute with button value (fixed the disappearing), and then I added parseInt() on my form elements to change their value to a number and get them added correctly. Again, thank you everyone! I'll see what I can do about closing this issue. – user8436420 Mar 17 '18 at 13:59

0 Answers0