如何创建仅允许数字,逗号和点的输入字段? [英] How can I create an input field that allows only numbers and comma and dot?

查看:131
本文介绍了如何创建仅允许数字,逗号和点的输入字段?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用select2.因此,它不是一个实数输入字段,我尝试创建一个仅允许带小数点的数字的输入字段:

I am using select2. So it is not a real number input field I try to create an input field that allows only numeric with decimal:

<input type="text" name="numeric" class='select2 allownumericwithdecimal'> 

 $(".allownumericwithdecimal").on("keypress keyup blur",function (event) {
        $(this).val($(this).val().replace(/[^0-9\.]/g,''));
        if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57)) {
          event.preventDefault();
        }
      });

我现在需要的是,它不仅允许指向,而且还应允许逗号.这是我的方法:

What I need now is, that it allows not only point, it should also allow comma. This is my approach:

 $(".allownumericwithdecimal").on("keypress keyup blur",function (event) {
        $(this).val($(this).val().replace(/[^0-9\.]/g,''));
        if ((event.which != 46 || $(this).val().indexOf('.') != -1 || $(this).val().indexOf(',') != -1) && (event.which < 48 || event.which > 57)) {
          event.preventDefault();
        }

仍然不允许使用逗号. });

Still no comma allowed.. });

推荐答案

我已经修复了您的代码

 $(".allownumericwithdecimal").on("keypress keyup blur",function (event) {
        $(this).val($(this).val().replace(/[^0-9\.|\,]/g,''));
        debugger;
        if(event.which == 44)
        {
        return true;
        }
        if ((event.which != 46 || $(this).val().indexOf('.') != -1) && (event.which < 48 || event.which > 57  )) {
        
          event.preventDefault();
        }
      });
        

<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="numeric" class='select2 allownumericwithdecimal'>

这篇关于如何创建仅允许数字,逗号和点的输入字段?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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