OmisNomis OmisNomis - 10 months ago 44
Javascript Question

Send form data to Javascript on submit

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)

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

And essentially all I want to do, when the
button is clicked, is have the value entered into the
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).


Something like this?

document.getElementById('theform').onsubmit = function() { 
    return false;

JSFiddle here:

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() { 
    return false;