Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to submit a form on enter when the textarea has focus?

Tags:

html

forms

When filling out a form's textarea, the default behavior when the enter key is hit is to move to the next line. How can I change the behavior of the form so it will submit upon user hitting enter even when the user is in a textarea?

I used Firebug to checkout Stack Overflow's comment textarea (which has this behaviour), but couldn't see any JavaScript that achieved this affect. Is there a way to change the behavior of the textarea without using JavaScript?

like image 352
andrew Avatar asked Dec 11 '10 20:12

andrew


People also ask

When should I use textarea over input?

Generally speaking an input field is a one-line field (probably to carry something like first name or last name, a phone number, an email). A textarea is a multi-line field that allows you to press ENTER! They are used for addresses or others long and complex type of data (also notes, for instance).

What makes a textarea different from a text input?

The difference between these both HTML field types is, that the input creates a smaller single line input box, while the textarea creates a bigger box meant for longer texts, like messages.


2 Answers

You can't do this without JavaScript. Stackoverflow is using the jQuery JavaScript library which attachs functions to HTML elements on page load.

Here's how you could do it with vanilla JavaScript:

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

Keycode 13 is the enter key.

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

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

with

$(document).ready(function() {     $('.commentarea').keydown(function(event) {         if (event.which == 13) {             this.form.submit();             event.preventDefault();          }     }); }); 
like image 85
BalusC Avatar answered Sep 21 '22 08:09

BalusC


Why do you want a textarea to submit when you hit enter?

A "text" input will submit by default when you press enter. It is a single line input.

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

A "textarea" will not, as it benefits from multi-line capabilities. Submitting on enter takes away some of this benefit.

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

You can add JavaScript code to detect the enter keypress and auto-submit, but you may be better off using a text input.

like image 32
jthompson Avatar answered Sep 22 '22 08:09

jthompson