开发者

How can I enter only numbers in TextBox using JavaScript without disable right click? [closed]

Closed. This question needs details or clarity. It is not currently accepting answers.

Want to improve this question? Add details and clarify the problem by editing this post.

Closed 2 years ago.

Improve this question

I want to allow numbers only to be allowed for a textbox and I already do it onkeydown event by allow only numbers and prevent ctrl+V but I have two problems :

  1. if I make right click then paste so any char can be entered and I want a solution without disable right 开发者_运维问答click by oncontextmenu="return false;"

  2. if I drag and drop any text it will be entered

Is there any solution that can work in all browsers without problem?


Just filter out the non numeric chars in the onchange event of your textbox and set it back to the textbox.


You can use onpaste event. You will be able to catch whenever something is pasted.
You can refer to Andy's answer regarding onpaste event.


I recently used jquery for this. Here's the code. Include your jquery file in your html.

<script type="text/javascript" src="js/vendor/jquery.validate.min.js"></script>

Include this script in your html.

<script>
$('#phoneNum').keypress(function(e) {
    var a = [];
    var k = e.which;

    for (i = 48; i < 58; i++)
        a.push(i);

    if (!(a.indexOf(k)>=0))
    {
        if(k != 45){
            e.preventDefault();
        }
    }
});
</script>

This is what your input will look like. phoneNume being the id.

<input type="tel" id="phoneNum" />
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜