How to submit a form when entering when textarea has focus?

When filling out the textarea form, the default behavior of pressing the enter key means going to the next line. How can I change the behavior of a form so that it feeds the userโ€™s input, even when the user is in a text field?

I used Firebug to test the Stack Overflow comment textarea (which has this behavior), but did not see any JavaScript that achieved this. Is there a way to change the behavior of a text field without using JavaScript?

+43
html forms
Dec 11 '10 at 20:35
source share
3 answers

You cannot do this without JavaScript. Stackoverflow uses the jQuery JavaScript library, which binds functions to HTML elements when the page loads.

Here you can do it using basic JavaScript:

<textarea onkeydown="if (event.keyCode == 13) { this.form.submit(); return false; }"></textarea> 

The key code is the enter key.

Here's how you could do it with jQuery, as Stackoverflow does:

 <textarea class="commentarea"></textarea> 

from

 $(document).ready(function() { $('.commentarea').keydown(function(event) { if (event.keyCode == 13) { this.form.submit(); return false; } }); }); 
+94
Dec 11 '10 at 20:47
source share

Why do you want the text field to be sent as you type?

Input "text" will be sent by default when you press the enter button. This is a single line input.

 <input type="text" value="..."> 

"textarea" will not be, as this may be useful for multi-line capabilities. Sending to input takes away part of this advantage.

 <textarea name="area"></textarea> 

You can add JavaScript code to detect keystrokes and send automatically, but you might be better off using text input.

+5
Dec 11 '10 at 20:45
source share
 <form id="myform"> <input type="textbox" id="field"/> <input type="button" value="submit"> </form> <script> $(function () { $("#field").keyup(function (event) { if (event.which === 13) { document.myform.submit(); } } }); </script> 
+3
Dec 11 '10 at 20:41
source share



All Articles