1

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

Result must 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.

Where did I miss on the javascript side?

Vikrant
  • 4,920
  • 17
  • 48
  • 72
Richard
  • 137
  • 1
  • 1
  • 12

3 Answers3

6

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

HTML

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

JQuery

    function onlyNum() {
      var $this = $('#txt');
      $this.val($this.val().replace(/\D/g, ''));
    }
Vikrant
  • 4,920
  • 17
  • 48
  • 72
1

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".

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.

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

And your jQuery selector would be:

$("input.numbers-only").on("paste", function(){  
    // do your stuff here
}); 
Vikrant
  • 4,920
  • 17
  • 48
  • 72
ste-fu
  • 6,879
  • 3
  • 27
  • 46
0

The jquery event should be:

$('#.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.

Community
  • 1
  • 1
Benjamin Ray
  • 1,855
  • 1
  • 14
  • 32