Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
409 views
in Technique[技术] by (71.8m points)

javascript - 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>?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...