js, jquery input box input limit can only enter the number 0 and positive integers, negative integers (input 0 in the first digit, and automatically clear the first digit 0 when entering a number greater than 0 in the second digit)

Requirements: Only 0, positive integer, and negative integer can be entered in the input box; only one negative sign can be entered and only the negative sign can be entered at the top; the first digit is entered with 0, and the second digit is automatically cleared when a number greater than 0 is entered Bit 0 (for example: 01 is 1; 00 is 0; -0 is 0).

1. Using onkeyup, you can only enter 0, positive integer, and negative integer. You can only enter a negative sign and you can only enter the negative sign at the top, but you cannot control the situation when you enter 0.

 

<input type="text" name="phone" class="layui-input" onkeyup="value=value.match(/^-?[0-9]\d*$/)||value.match(/-?/)">

2. To achieve the requirements, input first bind onkeyup, and then write a method to control input 0. I want to call multiple places on the page, just add the num-input class name to the input.

<input type="text" name="phone" class="layui-input num-input" onkeyup="value=value.match(/^-?[0-9]\d*$/)||value.match(/-?/)">

 

 

//输入框只能输入数字 0 正整数 负整数
$(document).on('input', '.num-input', function () {
    let val = $(this).val();
   //输入大于0的数字时候自动清空前面的0
    if (val > 0) {// 01 => 1
        if (val[0] == 0) {
            val = val.substr(1);
        }
    } else if (val == 0) {
        if (val[0] == 0) {// 00 => 0
            val = val.slice(0, 1);
        } else if(val[0] == "-"){ // -0 => 0
            val = 0;
        }
    } else {
        if (val[1] == 0) {// -2  在中间写0 -02 => 0
            val = 0;
        }
    }
    $(this).val(val);
});

 

Guess you like

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