如何防止输入中的波浪号 [英] How can I prevent tilde in input

查看:124
本文介绍了如何防止输入中的波浪号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想阻止在我的输入中键入代字号的可能性。

这是我的代码片段:



< script src =https://ajax.googleapis.com/ajax/libs/jquery/2.1.1>

 



我用 keydown keypressed keyup ,但它不能按预期工作。

任何人都可以得到一个简单的解决方案吗?

解决方案

有些人说你的代码有效,有些人不要。

因为,〜没有绑定在每个键盘布局的相同键上。

为了能够阻止为每个人编写(或粘贴)〜的可能性,我会做这样的事情:

 <(code> $('#myInput')。on(keyup,function(e){this.value = this.value.replace(/〜/ g,'');}) 

< script src =https://ajax.googleapis.com/ ajax / libs / jquery / 2.1.1 / jquery.min.js>< / script>< input id =myInput/>

我们可以看到每次我们尝试插入〜字符都被删除,但我认为这不是问题。相反,我认为这将帮助用户理解他不能使用该字符,而不怀疑其键盘的良好功能。

可以使用 input 而不是 keyup 来避免这种行为,但我个人更喜欢这种方式,因为上述原因。



<

通过修改正则表达式,可以添加一些其他被禁止的字符:



  $('#myInput' [〜^!] / g,'');}) 

< script src =https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js>< / script>< input id =myInput/ >< p> Forbidden:〜^!< / p>

我希望它有帮助。


I would like to block the possibility to type a tilde ~ in my input.
Here is a snippet of my code:

$('#myInput').on("keydown", function(e) {
  if (e.shiftKey && e.keyCode === 192) {
    e.preventDefault();
    console.log(e.keyCode);
  }
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

<input id="myInput" />

I tried the same as above with keydown, keypressed, keyup, but it is not working as intended.
Do anyone got a simple solution?

解决方案

Some people say your code works, some people don't.

Because, "~" isn't binded on the same keys on each keyboard layout.
To be able to block the possibility of writing (or pasting) "~" for everyone, I'll do something like this:

$('#myInput').on("keyup", function(e) {
  this.value = this.value.replace(/~/g, '');
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="myInput" />

We can see the "~" character been deleted each time we try to insert one, but I don't think that's an issue. Instead, I think that will help the user understand he can't use that character, without doubting about the good-functioning of their keyboard.
It's possible to use input instead of keyup to avoid that behaviour, but I personally prefer it that way for the above reasons.

⋅ ⋅ ⋅

This would be possible to add some other forbidden characters by modifying the regex:

$('#myInput').on("keyup", function(e) {
  this.value = this.value.replace(/[~^!]/g, '');
})

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input id="myInput" />
<p>Forbidden: ~ ^ !</p>

I hope it helps.

这篇关于如何防止输入中的波浪号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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