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?
10
votes
You're going to get much more help if you A) write in complete sentences, and B) show that you have tried to solve your problem. google.com/…
- Nick ODell
@Nick ODell - Thats not true Nick. A) Not everybody has a complete mastery of the english language, his question was easy enough to understand for @Tim to edit. B) No question is too trivial.
- John Farrell
2 Answers
30
votes
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();
}
});
3
votes
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();
}
});