23

Ok I feel like this should be really simple; so either I've completely missed the point of the questions on here and other websites I've read or it hasn't been asked in the same context....

I have a REALLY simple form element (below)

<form>
  <input type="text" id="searchTerm" />
  <input type="submit" value="Submit" id="submitButton" />
</form>

And essentially all I want to do, when the Submit button is clicked, is have the value entered into the text box passed to a JavaScript Function and console logged (for now).

This looks like it has been asked a million times but the questions I've read don't answer my question (I don't think).

Edit Thank you for all the responses; the biggest problem is I was trying to reference a function in an external Javascript file that was being called after the form element.

5
  • Have you actually tried to use javascript or jquery to solve this problem? Can you show us what you have tried so we have an idea of what to point out to you that would solve your question? Commented May 27, 2016 at 15:59
  • $("form").submit(function(){ // Do stuff }); Commented May 27, 2016 at 16:01
  • just use the onsubmit to invoke the function and get/log/dostuff with the values Commented May 27, 2016 at 16:01
  • 1
    use e.preventdefault otherwise the page would refresh and you would not see the log. Commented May 27, 2016 at 16:06
  • Does this answer your question? How can I listen to the form submit event in javascript? Commented May 6, 2020 at 10:56

8 Answers 8

57

It is not necessary to add yet another getElementById() inside the submit form handler function. I am confused as to why this approach is so common. What would you do if you needed to fetch multiple dozens / all values of the form? Write dozens of element selectors?

I think the following is much cleaner:

Inputs can include a name attribute which eases their access:

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

Even shorter,

function submitForm(that) {
  alert(that.searchTerm.value)
}
<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)">
  <input name="searchTerm"/>
  <button>Submit</button>
</form>

Because the handler itself has an implicit with(this) (details).

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>

Finally, to transform multiple inputs into a key-value object, you can use Object.fromEntries: (2)

function submitForm(event) {
  event.preventDefault()
  const obj = Object.fromEntries(new FormData(event.target).entries())
  // Prints: { searchTerm: "...", myCheckbox: "on" }
  console.log(obj)
  return false;
}
<form onsubmit="submitForm(event)">
  <input name="searchTerm"/>
  <input type="checkbox" name="myCheckbox"/>
  <button>Submit</button>
</form>

Sign up to request clarification or add additional context in comments.

2 Comments

IE doesn't support HTMLFormControlsCollection - the interface for event.target.elements - which is most likely why people are using element selectors.
Exactly what I was looking for. This should be the accepted answer. It is DRY and multiform friendly.
19

Something like this?

document.getElementById('theform').onsubmit = function() { 
    console.log(document.getElementById('searchTerm').value);
    return false;
};

JSFiddle here: https://jsfiddle.net/km7rt62v/

It's important to return false; to prevent default behaviour at the end of your submit handler, as otherwise the form will post and reload the page.

As others have demonstrated, it is also possible to use the onsubmit html attribute of the form element, it's a personal preference, but I prefer a cleaner separation between JS and HTML.

Edit: Since I got accepted answer and the question is tagged with jQuery, here's the jQuery equivalent:

$('#theform').submit(function() { 
    console.log($('#searchTerm').val());
    return false;
});

Comments

5

This is a pure simple JavaScript. You could use jQuery as well.

function checkForm(){
  console.log(document.getElementById('searchTerm').value);
  return false;
}
<form onsubmit='return checkForm();'>
  <input type="text" id="searchTerm" />
  <input type="submit" value="Submit" id="submitButton" />
</form>

7 Comments

No need for the javascript: label and you need the .value of the field
e.preventdefault()
return false also works - and works on more browsers and it is preventDefault, camel case
I wanted a function in an external Javascript file though? Is that possible?
@mplungjan. Thanks. I wrote it quickly and missed that :)
|
1

Submit form:

JS:

var searchForm= document.getElementById('searchForm');
var submitButton = document.getElementById('submitButton');

searchForm.onsubmit= function () {
  console.log(searchTerm.value);
};

HTML:

<form id="searchForm">
  <input type="text" id="searchTerm" />
  <input type="submit" value="Submit" id="submitButton" />
</form>

On click for button:

JS:

var searchTerm = document.getElementById('searchTerm');
var submitButton = document.getElementById('submitButton');

submitButton.onclick = function () {
  console.log(searchTerm.value);
};

HTML:

<form>
  <input type="text" id="searchTerm" />
  <input type="button" value="Submit" id="submitButton" />
</form>

See demo Here

Comments

0

there is an attribute you can use called onsubmit when you include an input with the type of submit in your form. Here is some documentation http://www.w3schools.com/tags/ev_onsubmit.asp.

The code would look something like this

<form onsubmit="submitForm()">
  <input type="text" id="searchTerm"/>
  <input type="submit" value="Submit" id="submitButton" />
</form>

<script>
  function submitForm() {
    let input = document.querySelector('#searchTerm');
    console.log(input.value);
    return false;
  }
</script>

3 Comments

You need to return false or preventDefault or the page will be reloaded
Can I get it to use an external JS file?
Certainly, just place the code in a file, for example script.js. Then in your html you do <script src="script.js"></script>
0

To have such a function in an external file, your best bet is to wire the submit event in an onload event:

window.onload=function() {
  document.getElementById("form1").onsubmit=function(e) {
    e=e?e:event;
    e.preventDefault(); // cancel the submit
    var val = document.getElementById("searchTerm").value;
    console.log(val);
  }  
}
<form id="form1">
  <input type="text" id="searchTerm" />
  <input type="submit" value="Submit" id="submitButton" />
</form>

jQuery version:

$(function() {
  $("#form1").on("submit",function(e) {
    e.preventDefault(); // cancel the submit
    var val = $("#searchTerm").val();
    console.log(val);
  }); 
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form id="form1">
  <input type="text" id="searchTerm" />
  <input type="submit" value="Submit" id="submitButton" />
</form>

Comments

0

You tagged this with jQuery, so here's a jQuery answer. What you need to use is the .submit() event handler.

$("form").submit(function(e) {
    console.log("form data: %o", $(this).find("#searchTerm").val());
    e.preventDefault();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<form>
    <input type="text" id="searchTerm" />
    <input type="submit" value="Submit" id="submitButton" />
</form>

This code will attach a handler to the <form> onsubmit event:

Comments

0

So the main issue was I had included the <script> element, linking to my external JavaScript file, at the bottom of my <body> element; meaning that at the time of the form being created it didn't know what Javascript Function I was talking about.

Thanks to all of those that helped, and this was the solution....

HTML

<head>
  <!-- jQuery library -->
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>
  <!-- Custom JavaScript -->
  <script src="js/wiki.js"></script>
</head>
<body>
  <form id="theform" onsubmit="test(this.searchTerm.value)">
    <input type="text" id="searchTerm" />
    <input type="submit" value="Submit" id="submitButton" />
  </form>
</body>
</html>

JavaScript

$(document).ready(function() {

  test = function(value) {
      console.log(value);
    return false;
  };

});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.