allowing input only for float number

后端 未结 7 531
别那么骄傲
别那么骄傲 2020-12-09 21:58

I have pain-time when making input that only allows float number with jquery library. my code can\'t prevent chacacter \".\" when it\'s becoming first input, can anyone guid

7条回答
  •  天命终不由人
    2020-12-09 22:39

    Here is my solution, works with negative numbers too (fiddle)

    $("input").keypress(function (event) {
        var inputCode = event.which;
        var currentValue = $(this).val();
        if (inputCode > 0 && (inputCode < 48 || inputCode > 57)) {
            if (inputCode == 46) {
                if (getCursorPosition(this) == 0 && currentValue.charAt(0) == '-') return false;
                if (currentValue.match(/[.]/)) return false;
            } 
            else if (inputCode == 45) {
                if (currentValue.charAt(0) == '-') return false;
                if (getCursorPosition(this) != 0) return false;
            } 
            else if (inputCode == 8) return true;
            else return false;
    
        } 
        else if (inputCode > 0 && (inputCode >= 48 && inputCode <= 57)) {
            if (currentValue.charAt(0) == '-' && getCursorPosition(this) == 0) return false;
        }
    });
    function getCursorPosition(element) {
        if (element.selectionStart) return element.selectionStart;
        else if (document.selection)
        {
            element.focus();
            var r = document.selection.createRange();
            if (r == null) return 0;
    
            var re = element.createTextRange(),
                rc = re.duplicate();
            re.moveToBookmark(r.getBookmark());
            rc.setEndPoint('EndToStart', re);
            return rc.text.length;
        }
        return 0;
    }
    

提交回复
热议问题