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>
?
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.
Yes, you can use textarea outside of form; there is no problem in it.
<textarea> does not support the value attribute.
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).
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;
}
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With