input限制只能輸入整數或保留小數點後2位的浮點數

暖楓無敵發表於2018-05-09

1、test.js檔案內容如下:

/**
 * 使用示例:  $("#price").decimalinput();//文字框只能輸入2位小數
 */

$.fn.decimalinput = function () {
    $(this).css("ime-mode", "disabled");
    this.bind("keypress", function (e) {
        if (e.charCode === 0) return true;  //非字元鍵 for firefox
        var code = (e.keyCode ? e.keyCode : e.which);  //相容火狐 IE
        if (code >= 48 && code <= 57) {
            var pos = getCurPosition(this);
            var selText = getSelectedText(this);
            var dotPos = this.value.indexOf(".");
            if (dotPos > 0 && pos > dotPos) {
                if (pos > dotPos + 2) return false;
                if (selText.length > 0 || this.value.substr(dotPos + 1).length < 2)
                    return true;
                else
                    return false;
            }
            return true;
        }
        //輸入"."
        if (code == 46) {
            var selText = getSelectedText(this);
            if (selText.indexOf(".") > 0) return true; //選中文字包含"."
            else if (/^[0-9]+\.$/.test(this.value + String.fromCharCode(code)))
                return true;
        }
        return false;
    });


    this.bind("blur", function () {
        if (this.value.lastIndexOf(".") == (this.value.length - 1)) {
            this.value = this.value.substr(0, this.value.length - 1);
        } else if (isNaN(this.value)) {
            this.value = "";
        }
        if (this.value) {
            this.value = parseFloat(this.value);//parseFloat(this.value).toFixed(2);
        }
        $(this).trigger("input");
        var value = this.value;
        var reg = /^(([1-9]\d*)(\.\d{1,2})?|0\.([1-9]|\d[1-9])|0)$/;
        if (reg.test(value)) {
            $(this).val(value);
            $("#errMsg").text("√");
        } else {
            $("#errMsg").text("×");
        }
    });


    this.bind("paste", function () {
        if (window.clipboardData) {
            var s = clipboardData.getData('text');
            if (!isNaN(s)) {
                value = parseFloat(s);
                return true;
            }
        }
        return false;
    });


    this.bind("dragenter", function () {
        return false;
    });


    this.bind("keyup", function () {


    });


    this.bind("propertychange", function (e) {
        if (isNaN(this.value))
            this.value = this.value.replace(/[^0-9\.]/g, "");
    });


    this.bind("input", function (e) {
        if (isNaN(this.value))
            this.value = this.value.replace(/[^0-9\.]/g, "");
    });
};
//獲取當前游標在文字框的位置
function getCurPosition(domObj) {
    var position = 0;
    if (domObj.selectionStart || domObj.selectionStart == '0') {
        position = domObj.selectionStart;
    }
    else if (document.selection) { //for IE
        domObj.focus();
        var currentRange = document.selection.createRange();
        var workRange = currentRange.duplicate();
        domObj.select();
        var allRange = document.selection.createRange();
        while (workRange.compareEndPoints("StartToStart", allRange) > 0) {
            workRange.moveStart("character", -1);
            position++;
        }
        currentRange.select();
    }


    return position;
}
//獲取當前文字框選中的文字
function getSelectedText(domObj) {
    if (domObj.selectionStart || domObj.selectionStart == '0') {
        return domObj.value.substring(domObj.selectionStart, domObj.selectionEnd);
    }
    else if (document.selection) { //for IE
        domObj.focus();
        var sel = document.selection.createRange();
        return sel.text;
    }
    else return '';
}

2、demo.html原始碼如下:

<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title></title>
    <script src="http://libs.baidu.com/jquery/1.7.2/jquery.min.js"></script>
    <script type="text/javascript">
        $(function() {
            $("#price").decimalinput();
        });
    </script>
    <script src="test.js"></script>
</head>
<body>
    <input type="text" id="price" maxlength="10" /><span id="errMsg"></span>
</body>
</html>

相關文章