Javascript 只允许数字粘贴

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29230254/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 10:15:43  来源:igfitidea点击:

Javascript allow only numeric paste

javascriptjqueryasp.net

提问by Richard

Javascript/jQuery:

Javascript/jQuery:

 $(document).ready(function () {
     $('#txt').bind("paste", function (e) {
         var $this = $(this);
         $this.val($this.val().replace(/[^\d.]/g, ''));
     });
 });

Html:

网址:

<asp:TextBox ID="txt" runat="server"></asp:TextBox>

If value as below

如果值如下

10-10-20.0a

Resultmust be as below

结果必须如下

1010200

I only want to allow it to paste numeric values to the textbox, otherwise, disable it. However, if I try the above javascript code, it is not working.

我只想让它将数值粘贴到文本框,否则,禁用它。但是,如果我尝试上面的 javascript 代码,它不起作用。

Where did I miss on the javascript side?

我在 javascript 方面错过了什么?

回答by Vikrant

Call the function onchangeevent of Textbox as, instead of document.ready:

changeTextbox 的事件上调用函数作为,而不是document.ready

HTML

HTML

<asp:TextBox ID="txt" runat="server" onchange="onlyNum()"></asp:TextBox>

JQuery

查询

    function onlyNum() {
      var $this = $('#txt');
      $this.val($this.val().replace(/\D/g, ''));
    }

回答by ste-fu

You need to make sure that you have your Client ID Mode set correctly, or the emitted text box will probably not have an ID of "txt".

您需要确保正确设置了客户端 ID 模式,否则发出的文本框可能没有“txt”的 ID。

https://msdn.microsoft.com/en-us/library/system.web.ui.control.clientidmode%28v=vs.110%29.aspx

https://msdn.microsoft.com/en-us/library/system.web.ui.control.clientidmode%28v=vs.110%29.aspx

<asp:TextBox ID="txt" runat="server" ClientIDMode="Static" ></asp:TextBox>

Another approach is to use CSS classes which can be very useful for re-use.

另一种方法是使用 CSS 类,这对于重用非常有用。

<asp:TextBox ID="txt" runat="server" CssClass="numbers-only" ></asp:TextBox>

And your jQuery selector would be:

你的 jQuery 选择器将是:

$("input.numbers-only").on("paste", function(){  
    // do your stuff here
}); 

回答by Benjamin Ray

The jquery event should be:

jquery 事件应该是:

$('#.txt').on('paste', function() {...});

See example here: Catch paste input

请参阅此处的示例:捕获粘贴输入

Note the use of a timeout to allow the value to be pasted before you manipulate it.

请注意使用超时以允许在操作之前粘贴该值。

Once you properly handle the event and get the pasted value, you can add your validation.

正确处理事件并获得粘贴的值后,您可以添加验证。

Also see ste-fu's answer about referencing the proper field, as asp.net will by default append the container's is to your text box id and the selector '#txt' won't work.

另请参阅 ste-fu 关于引用正确字段的回答,因为 asp.net 默认情况下会将容器的 is 附加到您的文本框 id 并且选择器“#txt”将不起作用。