The input limit of js and jquery input box can only input the number 0 and positive integer (input 0 in the first digit, and automatically clear the 0 in the first digit when inputting a number greater than 0 in the second digit)

  The input box can only enter the number 0 and positive integers (the first digit is 0, and the second digit is automatically cleared when a number greater than 0 is entered). I want to call in multiple places on the page and add the num-input class to the input. The name will do.

<input type="text" name="email" autocomplete="off" class="layui-input num-input">
//输入框只能输入数字 0 正整数
$(document).on('input', '.num-input', function () {//也可以绑定keyup事件
    // onkeyup="value=value.replace(/^(1+)|[^\d]+/g,'')"
    let val = $(this).val();
    //只能输入数字
    val = val.replace(/\D/g, "");
    //第一位输入0,第二位输入大于0的数字时候自动清空第一位的0
    if (val > 0) {//01 = > 1
        if (val[0] == 0) {
            val = val.substr(1);
        }
    } else if (val == 0) {// 00 => 0
        val = val.slice(0, 1);
    }
    $(this).val(val);
});

 

 

Guess you like

Origin blog.csdn.net/qq_40015157/article/details/112601709