0

Javascript beginner here - I looked up a bunch of answers on similar questions, but they all use PHP which I don't know anything about. I was hoping to do the following in pure Javascript:

I have a input field and a button:

<!DOCTYPE html>
<html>
  <head>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width">
  </head>
  <body>
    <form>
     
      <label for="someNum">Some number:</label>
      <input type="number" id="someNum">

      <input type="submit" id="button" value="Submit">
    </form>

    <script src="script.js"></script>

  </body>
</html>

When I hit "Submit", I want to console.log the value of someNum:

const button = document.getElementById("button")
button.addEventListener("click", calculate)

function calculate () {
   let someNum = document.getElementById("someNum").value
   console.log(someNum)
}

However, upon clicking "Submit", the value entered by the user is no longer shown in the form. How do I prevent that?

vauss
  • 49
  • 7
  • 1
    Replace your submit- with a click button, if you don’t want to actually submit the form in the first place. Or, prevent the default action of the submit button click. – CBroe Jul 12 '21 at 12:03
  • Prevent the default event handler from running. – Dave Newton Jul 12 '21 at 12:03
  • don't use a form if you don't want to submit a form – Bravo Jul 12 '21 at 12:05
  • 1
    Does this answer your question? [How to prevent form from being submitted?](https://stackoverflow.com/questions/3350247/how-to-prevent-form-from-being-submitted) – ikiK Jul 12 '21 at 12:08
  • 1
    Unrelated, but PHP isn't relevant to this question--PHP runs on the server, and other thanby rendering HTML and JS for use on the client cannot be used to control anything on the client side. – Dave Newton Jul 12 '21 at 12:31

0 Answers0