osman Rahimi
osman Rahimi

Reputation: 1507

don't can use Enter key from textarea

In my project I need diable Enter key for some textbox , because i don't want post page when enter key button . I use this Code for disable Enter key :

$(document).keypress(
function (event) {
    if (event.which == '13') {
        event.preventDefault();
    }
});

Its work fine , but when Add textarea in page , I cant enter key for break line , because Enter key disabled .

how can I enable Enter key for textarea?

Upvotes: 0

Views: 1493

Answers (2)

Saumil
Saumil

Reputation: 2517

You should bind your form to detect the Enter key as,

$('#formid').on("keyup keypress", function(e) {
  var code = e.keyCode || e.which; 
  if (code  == 13) {               
    e.preventDefault();
    return false;
  }
});

Here is a demo

By this you will be able to use the Enter key on your text area without submitting the form.

Upvotes: 0

AmmarCSE
AmmarCSE

Reputation: 30607

I don't know if its recommended to attach a global keypress handler like that. Regardless, the easiest way out would be

$(document).on('keypress', 
function (event) {
    if (event.which == '13' && event.target.tagName != 'TEXTAREA') {
        event.preventDefault();
    }
});

In the above, you are checking the tagName of event.target to see if the element in which the enter occured is a textarea or not

However, I would recommend this approach

$('form').on('keypress', 'form',
    function (event) {
        if (event.which == '13') {
            event.preventDefault();
        }
    });

This will target all input elements and not textarea elements,

Upvotes: 4

Related Questions