如何创建仅允许数字、逗号和点的输入字段?

pea*_*ove 1 jquery input function jquery-select2

我正在使用 select2。所以它不是一个实数输入字段我尝试创建一个仅允许带小数的数字的输入字段:

<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();
        }
      });
Run Code Online (Sandbox Code Playgroud)

我现在需要的是,它不仅允许点,还应该允许逗号。这是我的方法:

 $(".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();
        }
Run Code Online (Sandbox Code Playgroud)

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

cha*_*ati 7

我已经修复了你的代码

 $(".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();
        }
      });
        
Run Code Online (Sandbox Code Playgroud)
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input type="text" name="numeric" class='select2 allownumericwithdecimal'>
Run Code Online (Sandbox Code Playgroud)