簡體   English   中英

如何在手動輸入時限制html5數字輸入的最大值

[英]How to restrict max value on html5 number input on manual entry

免費的jqgrid列定義為使用html5數字輸入類型,例如

{ name: "amount", width: 62, template: "number",
             formatter: "number", formatoptions: {decimalSeparator:",", thousandsSeparator: " ", decimalPlaces: 4, defaultValue: '0.0000'},
               editoptions: {
                   maxlength; 4
                   type: "number", 
                   max: 9999
               } },

它允許從鍵盤輸入大於9999的數字。 max: 9999僅影響使用微調器輸入。

如何解決此問題,使鍵盤輸入不能超過9999?

測試用例在

http://jsfiddle.net/jhckz7rr/3/

它允許在“金額”列中手動輸入大於9999的數字。 如何將手動輸入限制為9999? 我也嘗試過使用字符串最大值max: '9999'但問題仍然存在。

大

如果輸入類型是文本,則輸入將遵循maxlength值。

嘗試使用以下內容

{
    name: "amount",
    width: 62,
    template: "number", // formatter: "number"
    formatoptions: {
        decimalSeparator: ",",
        thousandsSeparator: " ",
        decimalPlaces: 2,
        defaultValue: "0,00"
    },
    editoptions: {
        maxlength: 7,
        type: "number",
        max: "9999",
        dataEvents: [
            {
                type: "blur",
                fn: function (e) {
                        if (e.target.checkValidity()) {
                            $(e.target).removeClass("ui-state-error");
                        } else {
                            $(e.target).addClass("ui-state-error");
                            alert(e.target.validationMessage);
                            $(e.target).focus();
                        }
                    }
            }
        ]
    }

}

上面的代碼調用<input type="number"> checkValidity()方法。 當然,您需要在代碼中包括其他測試,例如驗證e.target.checkValidity是一個函數(對於在舊的Web瀏覽器中執行的情況)以及其他一些函數。 上面的代碼僅顯示了使用<input type="number">功能進行驗證的主要思想。

請參閱演示http://jsfiddle.net/OlegKi/jhckz7rr/8/ ,該演示可用於內聯編輯和表單編輯。

使用jQuery創建輸入驗證。

事件偵聽器在編輯單擊時附加,在保存單擊時被刪除。 我使用setTimeout與free-jqgrid元素操作進行同步-正確的解決方案是擴展free-jqgrid功能

function restrictMax(){

    var max = parseFloat($(this).attr('max'))
    var value = parseFloat($(this).val())
    if($(this).val() > max){
        $(this).val(max)
    }
}
setTimeout(function(){
    $('.fa-pencil').click(function(){ //click on edit
        var thatParent = $(this).closest('tr')
        setTimeout(function(){

            thatParent.find('input[type="number"]').on('input',restrictMax)
        },0);
    })
    $('.fa-floppy-o').click(function(){ //click on save
        var thatParent = $(this).closest('tr')
        setTimeout(function(){
            thatParent.find('input[type="number"]').off('input',restrictMax)
        },0)
    })

},0)

http://jsfiddle.net/jhckz7rr/6/

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM