簡體   English   中英

如何阻止在textarea中輸入回車?

[英]How to block entering carriage return in textarea?

在按鍵事件期間,如何使用asp.net mvc阻止在textarea中輸入回車符,新行,單引號和雙引號?

您可以使用jquery並訂閱textarea的.keypress()事件:

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

為了適應由用戶拖放文本區域內的其他文本/元素或通過粘貼其中的文本而導致的文本修改,有必要在change事件中進行監聽。

此外,我建議使用自jQuery 1.7以來可用的.on()方法,並檢測用戶通過事件對象的event.which屬性按下的回車鍵,以使應用程序具有可靠的跨瀏覽器行為:

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();
    }
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM