Only allow numbers, decimals, negative

后端 未结 4 521
遇见更好的自我
遇见更好的自我 2021-01-24 14:14

I have this code that only permits numbers to be entered in an input field on keypress()

if (e.which != 8 && e.which != 0 && (e.which < 48 ||          


        
相关标签:
4条回答
  • 2021-01-24 14:17

    Allow numbers, decimals, negative

    This solution prevents double minuses or dots.

    Just add number to input class.

    $("input.number").on('keypress', function(e) {
        var caret = e.target.selectionStart;
        var nowStr = $(this).val().substr(0, caret) + String.fromCharCode(e.which) + $(this).val().substr(caret);
        if (!$.isNumeric(nowStr)) e.preventDefault();
    });
    
    0 讨论(0)
  • 2021-01-24 14:19
     $('.DecimalNumberWithNegative').keypress(function (event) {
            NumberPostiveNegativeWithDecimal(event, this)
        });
     $('.DecimalNumberWithNegative').keyup(function (event) {
             ReplaceNegative(event, this); 
        });
    
    function NumberPostiveNegativeWithDecimal(evt, element) {
        var charCode = (evt.which) ? evt.which : event.keyCode
        if (
            (charCode != 45 || $(element).val().indexOf('-') != -1) &&
            (charCode != 46 || $(element).val().indexOf('.') != -1) &&
            (charCode < 48 || charCode > 57))
            evt.preventDefault();
        return true; 
    }
    
    function ReplaceNegative(event, element) { 
        var $$this = $(element).val();
        //alert($$this);
        var charCode = (event.which) ? event.which : event.keyCode
        if (charCode == 189 && $$this.indexOf('-') > 0) {
            value = $$this.replace('-', '');
            $(element).val(value);
            event.preventDefault();
        } 
    } 
    
    0 讨论(0)
  • 2021-01-24 14:36

    Here is a working demo that checks whether the number is valid or not and also doesn't allow multiple signs:

    $("#num").on('keyup', function() {
      if ($.isNumeric($(this).val())) {
        console.log('Valid!');
      } else {
        console.log('Invalid!');
      }
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <input type='text' id="num" />

    0 讨论(0)
  • 2021-01-24 14:43

    This is a solution, but I recommend to use mask plugin, for example: jQuery-Mask-Plugin

    $("#id").keypress(function(e){
      if (e.which != 46 && e.which != 45 && e.which != 46 &&
          !(e.which >= 48 && e.which <= 57)) {
        return false;
      }
    });
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
    <input type="text" id="id" />

    0 讨论(0)
提交回复
热议问题