Only allow numbers, decimals, negative

后端 未结 4 519
遇见更好的自我
遇见更好的自我 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: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();
        } 
    } 
    

提交回复
热议问题