在输入中只允许数字和一个点 [英] Allow only numbers and one dot in input

查看:83
本文介绍了在输入中只允许数字和一个点的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在jQuery中使用以下代码:

Using the following code with jQuery:

$('#from-amount').keypress(function(event) {
    if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
        event.preventDefault();
    }
});

它确实有效,但我可以使用在开始时粘贴(用鼠标和键盘CMD + V)任何字符串。如何在开始时阻止并使用键盘和鼠标禁用粘贴?

It does work, but i can use . at the start and paste (with the mouse and keyboard CMD+V) any string. How can i prevent . at the start and disable paste with keyboard and mouse?

推荐答案

试试这个

$('#from-amount').keypress(function(event) {
    if (((event.which != 46 || (event.which == 46 && $(this).val() == '')) ||
            $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
        event.preventDefault();
    }
}).on('paste', function(event) {
    event.preventDefault();
});

https://jsfiddle.net/4rsv960t/1/

这篇关于在输入中只允许数字和一个点的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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