Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to block entering carriage return in textarea?

How do I block entering carriage return, new line, single quotes and double quotes in a textarea using asp.net mvc, during the key press event?

like image 549
user616839 Avatar asked May 19 '11 01:05

user616839


2 Answers

You could use jquery and subscribe for the .keypress() event of the textarea:

$('textarea').keypress(function(event) {
    // Check the keyCode and if the user pressed Enter (code = 13) 
    // disable it
    if (event.keyCode == 13) {
        event.preventDefault();
    }
});
like image 173
Darin Dimitrov Avatar answered Nov 05 '22 07:11

Darin Dimitrov


To be comfortable with text modification caused by user's drag and drop of other text/elements inside the textarea or by pasting text inside it, it is necessary listening at the change event, too.

Moreover, I suggest to use the .on() method, available since jQuery 1.7, and to detect the enter key pressed by the user through the event.which property of the event object, to have a solid cross-browser behaviour of your app:

var $textarea = $('#comment');
// events to bind:
$textarea.on('keydown keyup change focus blur', function(e) {
    if (e.type === 'change') {
        // this event is triggered when the text is changed through drag and drop too,
        // or by pasting something inside the textarea;
        // remove carriage returns (\r) and newlines (\n):
        $textarea.val($textarea.val().replace(/\r?\n/g, ''));
    }
    if (e.which === 13) {
        // the enter key has been pressed, avoid producing a carriage return from it:
        e.preventDefault();
    }
});
like image 43
yodabar Avatar answered Nov 05 '22 07:11

yodabar