不要在textarea中添加新行 [英] Don't allow new lines in textarea

查看:170
本文介绍了不要在textarea中添加新行的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用jQuery我怎么能不允许插入新的行(通过按下输入或复制文本) - 在半伪代码...

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

谢谢!

编辑: >

会不会像以下那样粗俗?还是有更好的办法?

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

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


解决方案

有两种方法可以做到这一点:检查每个字符因为它是输入,如果你不希望它显示,返回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, ''));
});

这篇关于不要在textarea中添加新行的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆