javascript - Make the Enter key to not create a line break - Stack Overflow

I have a textarea field and it's data will be submitted using java script and ajax by pressing ent

I have a textarea field and it's data will be submitted using java script and ajax by pressing enter key, the problem is that when the user press the enter key first it will create a new line then the textarea will be submitted, and i don't want it to create a new line.

Please help!

I have a textarea field and it's data will be submitted using java script and ajax by pressing enter key, the problem is that when the user press the enter key first it will create a new line then the textarea will be submitted, and i don't want it to create a new line.

Please help!

Share Improve this question asked Jun 27, 2015 at 4:25 Mohammad Samim SamimeeMohammad Samim Samimee 572 silver badges8 bronze badges 1
  • 1 With jquery, bind the keyup event of the textarea, capture the event object in the first argument. Use this object to cancel event when the pressed key is enter. I believe it s code is 13. jQuery has all the doc for that, SO all the posts for that also. One thing not to do is to cancel the propagation, otherwise you may need to also trigger submit event at that point. – user4466350 Commented Jun 27, 2015 at 4:28
Add a ment  | 

2 Answers 2

Reset to default 8

Just listen to the keydown event and prevent the default action (which is the linebreak)

$("textarea").on("keydown", function(e) {
    if(e.which === 13) { // enter key
        e.preventDefault(); // prevents linebreak
        // here you could add your submit call
        return false;
    }
});

You can use jQuery to determine whether the textarea is active:

$("#foo").is(":focus") // expression is true only when it is active

So your code should look something like this:

if (<enter key pressed> and !($("#foo").is(":focus")))
  <submit with JavaScript and Ajax>

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744193593a4562547.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信