user5159158
user5159158

Reputation:

How to disable paste option for string part only not for numeric?

I have a textbox that accept only numbers. I have done that part but problem is that I can not disable the paste option of textbox i.e., onPaste="return false;". So, string can be entered through paste option. So, how to disable paste option for string part only not for numeric?

function OnlyNumbers()
{
if (event.keyCode <= 46 || event.keyCode > 57 || event.keyCode == 47) event.returnValue = false;
}

<asp:TextBox ID="txtRecApr" class="txt" autocomplete="off" 
onKeyPress="OnlyNumbers()" onfocus="javascript:this.select();" 
runat="server" Width="60px" MaxLength="5" AutoPostBack="True" 
onPaste="return false;" ontextchanged="txtRecApr_TextChanged">
</asp:TextBox>

Upvotes: 4

Views: 135

Answers (1)

Litisqe Kumar
Litisqe Kumar

Reputation: 2564

Try this script. Hope this may help you.

<script type="text/javascript">  

            $(document).ready(function () {  
                var keyDown = false, ctrl = 17, vKey = 86, Vkey = 118;  

                $(document).keydown(function (e) {  
                    if (e.keyCode == ctrl) keyDown = true;  
                }).keyup(function (e) {  
                    if (e.keyCode == ctrl) keyDown = false;  
                });  

                $('input[type=text]').on('keypress', function (e) {  
                    if (!e) var e = window.event;  
                    if (e.keyCode > 0 && e.which == 0) return true;  
                    if (e.keyCode) code = e.keyCode;  
                    else if (e.which) code = e.which;  
                    var character = String.fromCharCode(code);  
                    if (character == '\b' || character == ' ' || character == '\t') return true;  
                    if (keyDown && (code == vKey || code == Vkey)) return (character);  
                    else return (/[0-9]$/.test(character));  
                }).on('focusout', function (e) {  
                    var $this = $(this);  
                    $this.val($this.val().replace(/[^0-9]/g, ''));  
                }).on('paste', function (e) {  
                    var $this = $(this);  
                    setTimeout(function () {  
                        $this.val($this.val().replace(/[^0-9]/g, ''));  
                    }, 5);  
                });  
            });  
        </script>

EDIT:

I will provide a brief view. As you said that you have done that part which accepts only numeric value. So, I will not focus on that. As you can see that I have used replace(/[^0-9]/g, ''). It will replace all chars which are not match with range 0-9 on focusout and on paste. For more information visit Here.

Upvotes: 1

Related Questions