input輸入框爲數字(number)類型時maxlength屬性不起作用

使用html代碼解決

<input type="number" maxlength="5" oninput="if(value.length>5)value=value.slice(0,5)" />

使用js代碼解決

//輸入框爲數字類型時防止maxlength屬性不起作用
$('input').bind('input propertychange', function() {
    if($(this).attr("type")=="number"){
        //獲取輸入框的最大長度
        var mxaL= $(this).attr("maxlength");
        //如果輸入的長度超過最大長度
        if($(this).val().length>mxaL){
            $(this).val($(this).val().slice(0,mxaL));
        }
    }
});
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章