且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

不要在textarea中添加新行

更新时间:2023-12-03 15:25:52

有两种方法可以做到这一点:检查每个字符因为它是输入,如果你不希望它显示,返回false,或在每个更改/键盘上你可以检查整个内容。虽然前者更高性能,但在用户粘贴包含不需要的字符的内容的情况下将不起作用。出于这个原因,我推荐后一种方法,像这样(这将不允许所有垂直空白):

$ $ $ $'''textarea ').on('keyup',function(){
$(this).val($(this).val()。replace(/ [\r\\\
\v] + / g ,''));
});


Using jQuery how can I not allow new lines to be inserted (by pressing enter or copying in text) - In semi-pseudo code...

$('textarea').keydown(function(){
 $(this).remove_new_lines();
});

Thanks!

EDIT:

Would it be as crude as the following or is there a better way?

function removeNL(s){ 
  return s.replace(/[\n\r\t]/g,); 
}

$('textarea').keydown(function(){
 $(this).val(removeNL($(this).val));
});

There are two methods to do this: check each character as it is input and return false if you don't want it to show up, or on each change/keyup you can check the entire contents. While the former is more performant, it won't work in situations where the user pastes content in that includes unwanted characters. For that reason, I recommend the latter approach, something like this (which will disallow all vertical whitespace):

$('textarea').on('keyup', function(){
  $(this).val($(this).val().replace(/[\r\n\v]+/g, ''));
});