Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Submitting data from textarea by hitting "Enter"

I have dynamic web page with JS. There is a <textarea> and a Send button, but no <form> tags. How do I make Submit button fire and the <textarea> get cleared when Enter is pressed in the <textarea>?

like image 963
Alex Avatar asked Apr 25 '09 20:04

Alex


People also ask

Can I use textarea as input HTML?

To add a multi-line text input, use the HTML <textarea> tag. You can set the size of a text area using the cols and rows attributes. It is used within a form, to allow users to input text over multiple rows. Specifies that on page load the text area should automatically get focus.

Can textarea be used outside form?

Yes, you can use textarea outside of form; there is no problem in it.

Can we use value attribute in textarea?

<textarea> does not support the value attribute.

What is textarea form element used for How does the user enter data?

The <textarea> tag defines a multi-line text input control. The <textarea> element is often used in a form, to collect user inputs like comments or reviews. A text area can hold an unlimited number of characters, and the text renders in a fixed-width font (usually Courier).


2 Answers

You could use an keyup handler for the textarea (although I would advise against it*).

[SomeTextarea].onkeyup = function(e){
  e = e || event;
  if (e.keyCode === 13) {
    // start your submit function
  }
  return true;
 }

*Why not use a text input field for this? Textarea is escpecially suited for multiline input, a text input field for single line input. With an enter handler you criple the multiline input. I remember using it once for a XHR (aka AJAX) chat application (so the textarea behaved like an MSN input area), but re-enabled multiline input using the CTRL-enter key for new lines. May be that's an idea for you? The listener would be extended like this:

[SomeTextarea].onkeyup = function(e){
  e = e || event;
  if (e.keyCode === 13 && !e.ctrlKey) {
    // start your submit function
  }
  return true;
 }
like image 116
KooiInc Avatar answered Oct 10 '22 14:10

KooiInc


Hitting Enter in a textarea inserts a line break, rather than submitting the parent form; this would't work in that fashion even with regular form tags.

It would be inadvisable to attempt to work around this behaviour, as it would violate the user's expectation of how text area controls behave, both in other web sites, and in other applications on their platform.

like image 37
Rob Avatar answered Oct 10 '22 12:10

Rob