Skip to content

Get form data on submit JavaScript

  • by

Use the JavaScript onsubmit() event in the form tag to Get form data on submit. Inputs can include a name the attribute which eases their access:

  function submitForm(event) {
    alert(event.target.elements.searchTerm.value)
    return false;
  }
<form onsubmit="submitForm(event)">
  <input name="searchTerm"/>
  <button>Submit</button>
</form>

Even better,

function submitForm(that) {
  alert(that.searchTerm.value)
  return false;
}
<form onsubmit="submitForm(this)">
  <input name="searchTerm"/>
  <button>Submit</button>
</form>

In the handler itself, you can even access values directly:

<form onsubmit="alert(searchTerm); false">
  <input name="searchTerm"/>
  <button>Submit</button>
</form>

If you register the event handler via JS, the this (in non-lambda functions) already points to the form element, so you can also do

document.querySelector('#myForm').addEventListener('submit', function() {
  event.preventDefault()
  alert(this.elements.searchTerm.value)
});
<form id="myForm">
  <input name="searchTerm"/>
  <button>Submit</button>
</form>

Source: stackoverflow.com

Get form data on submitting JavaScript

Simple example code.

<!DOCTYPE html>
<html>
<body>
  <form onsubmit="submitForm(event)">
    <input name="searchTerm"/>
    <button>Submit</button>
  </form>

  <script>
    function submitForm(event) {
      alert(event.target.elements.searchTerm.value)
      return false;
    }
  </script>
</body>
</html>

Output:

Get form data on submit JavaScript

If you want to get a key/value mapping (plain) object out of an HTML form, see this answer.

Do comment if you have any doubts or suggestions on this JS submit topic.

Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.

OS: Windows 10

Code: HTML 5 Version

Leave a Reply

Discover more from Tutorial

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

Continue reading