javascript 如何阻止在textarea中输入回车?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/6052712/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to block entering carriage return in textarea?
提问by user616839
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?
在按键事件期间,如何使用 asp.net mvc 在 textarea 中阻止输入回车、换行、单引号和双引号?
回答by Darin Dimitrov
You could use jquery and subscribe for the .keypress()
event of the textarea:
您可以使用 jquery 并订阅.keypress()
textarea的事件:
$('textarea').keypress(function(event) {
// Check the keyCode and if the user pressed Enter (code = 13)
// disable it
if (event.keyCode == 13) {
event.preventDefault();
}
});
回答by Emanuele Del Grande
To be comfortable with text modification caused by user's drag and dropof other text/elements inside the textarea or by pastingtext inside it, it is necessary listening at the change
event, too.
为了适应由于用户在 textarea 内拖放其他文本/元素或在其中粘贴文本而导致的文本修改,也有必要在change
事件中收听。
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:
此外,我建议使用.on()
自 jQuery 1.7 起可用的方法,并通过event.which
事件对象的属性检测用户按下的 Enter 键,以使您的应用程序具有可靠的跨浏览器行为:
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();
}
});