Monday, May 13, 2024
 Popular · Latest · Hot · Upcoming
29
rated 0 times [  34] [ 5]  / answers: 1 / hits: 68058  / 8 Years ago, fri, may 27, 2016, 12:00:00

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.


More From » jquery

 Answers
0

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

[#61995] Thursday, May 26, 2016, 8 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
benitoh

Total Points: 150
Total Questions: 113
Total Answers: 104

Location: India
Member since Wed, Aug 26, 2020
4 Years ago
benitoh questions
Sun, Mar 21, 21, 00:00, 3 Years ago
Mon, May 13, 19, 00:00, 5 Years ago
;