search

Home  >  Q&A  >  body text

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

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!

世界只因有你世界只因有你2707 days ago1420

reply all(4)I'll reply

  • 三叔

    三叔2017-06-28 09:29:53

    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

    reply
    0
  • 天蓬老师

    天蓬老师2017-06-28 09:29:53

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

    reply
    1
  • ringa_lee

    ringa_lee2017-06-28 09:29:53

    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 = '';
        }
    };

    reply
    0
  • 世界只因有你

    世界只因有你2017-06-28 09:29:53

    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

    reply
    0
  • Cancelreply