javascript - How does js determine that the input value is a number, not less than or equal to 0, without using alert, but using red font on the same line to prompt the user
世界只因有你
世界只因有你 2017-06-28 09:27:53
0
4
1416

How does js determine that the input value is a number, not less than or equal to 0, and can be a decimal. If the conditions are not met, will prompt the user with red words after %, TKS!

世界只因有你
世界只因有你

reply all(4)
三叔

Determine whether the focus is within the input (or pass the focus leave event)
Then pass the value to the js method class for judgment. Judge according to your requirements

Peter_Zhu
document.getElementById('ratio').onchange = function(){
    var val = this.value;
    if( val * 1 == NaN || val <= 0 )
    return false; //报错
    
    //正确代码
};

document.getElementById('ratio').onkeyup = function(){}; //也行
ringa_lee

CSS:

.red_border {
    border: 1px solid red; // 红框样式
}

.red_text {
    color: red; // 红色提示文字样式
}

HTML:

<td class="form-inline">
    <input type="text" class="form-control" name="post[post_ratio]" id="ratio" required value="" />&nbsp;&nbsp; %
    <span class="red_text"></span>
</td>

Javascript:

document.getElementById('ratio').onchange = function() {
    var val = this.value;
    var tip = this.getElementsByClassName('red_text')[0];

    if(isNaN(+val) || (!isNaN(+val) && +val <= 0)) {
        // 错误
        this.className = 'red_border';
        tip.innerHTML = '出现错误';
    } else {
        this.className = '';
        tip.innerHTML = '';
    }
};
世界只因有你

Short answer for mobile phones, add the pattern attribute to the input, use regularity to verify the content, and then use input:invalid in the css to mark the illegal content in the input in red (just a red box with red text or something), and the red text behind it will prompt p. Write with input, then use

p {display:none;color:red;}
input:invalid+p {display:block;}

After setting up such rules, it should be almost the same (if the label is replaced with the ID, I won’t have to code more on my phone). However, if you need to be compatible with IE9, you may need to write another compatible one...


Reference:

MDN - Form Validation

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template