javascriptjqueryhtmlforms

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)

<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.


Solution

  • 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;
    });