如何阻止在文本区域输入回车符?

发布于 2024-11-08 11:19:22 字数 57 浏览 0 评论 0原文

如何在按键事件期间使用 asp.net mvc 阻止在文本区域中输入回车符、换行符、单引号和双引号?

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?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

写给空气的情书 2024-11-15 11:19:22

您可以使用 jquery 并订阅 .keypress() 事件文本区域:

$('textarea').keypress(function(event) {
    // Check the keyCode and if the user pressed Enter (code = 13) 
    // disable it
    if (event.keyCode == 13) {
        event.preventDefault();
    }
});

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();
    }
});
Bonjour°[大白 2024-11-15 11:19:22

为了适应由用户在文本区域内拖放其他文本/元素或在其中粘贴文本引起的文本修改,有必要监听 更改 事件也是如此。

此外,我建议使用自 jQuery 1.7 起可用的 .on() 方法,并通过该方法的 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();
    }
});

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();
    }
});
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文