Handling Enter Key on Text Area using javascript

对着背影说爱祢 提交于 2019-12-04 18:01:39
Baz1nga

http://jsfiddle.net/26kN7/1/

$("textarea").keyup(function(e) {
   var code = e.keyCode ? e.keyCode : e.which;
   if (code == 13) {  // Enter keycode
     if($(this).hasClass("first")) {
        alert("first ta clicked");
     } else {
         alert("the other ta clicked");
     }
   }
});

in some versions of FFX pressing <Tab>, e.which isn't set (remains 0), but e.keyCode is (9).

you can also shorten this to

$("textarea").keyup(function(e){
    if((e.keyCode || e.which) == 13) { //Enter keycode
      if($(this).hasClass("first")) {
        alert("first ta clicked");
      } else {
        alert("the other ta clicked");
      }
    }
});

the other thing note is I like adding the class here than finding the first textarea is cos this is more generic solution and could cater to any of the textareas.

You could try using:

$('textarea').keypress(
    function(e){
        if (e.keyCode == 13) {
            if ($(this).index() == 0) {
                // code for first textarea;
            }
            else {
                // code for others
            }
        }
    });

JS Fiddle demo.

Check the which property of the jQuery event object to determine which key was pressed.

$('textarea').first().keypress(function (e)
{
    if (e.which === 13) alert('Text Area 1 enter key pressed');
}).nextAll().keypress(function (e)
{
    if (e.which === 13) alert('Other Text Area enter key pressed');
});
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!