Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Handling Enter Key on Text Area using javascript

I have 5 text areas on a page and I would like a specific event to occur on hitting the enter key on the first text area and a different event on enter key of the other text areas. Can you please suggest on how this can be acheived.

<TextArea></TextArea>
<TextArea></TextArea>
<TextArea></TextArea>
<TextArea></TextArea>
<TextArea></TextArea>

when hitting the enter on 1st Text Area, alert('Text Area 1 clicked');

when hitting the enter on the other 4 Text Area, alert ('Other Text Area's clicked');

Can this be acheived using jquery.

like image 235
Abishek Avatar asked Apr 26 '26 11:04

Abishek


2 Answers

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.

like image 180
Baz1nga Avatar answered Apr 28 '26 23:04

Baz1nga


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.

like image 38
David Thomas Avatar answered Apr 29 '26 01:04

David Thomas



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!