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?
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();
}
});
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();
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With