HTML/JS:onblur函数查看是否按下了特定按钮


HTML/JS: onblur function to see if a particular button is being pressed

我有客户端验证,如果在onblur过程中HTML文本输入字段为空,则会在屏幕上显示"value required"消息。除了特殊情况下用户点击此表单的提交按钮外,此操作效果良好。

提交缺少文本的表单会导致服务器端验证失败,从而导致更明显的错误消息。我的问题是,在加载新页面之前,模糊消息会持续很短的时间。

这不是功能问题,但看起来确实有点不专业。编辑:为了清楚起见,我应该提到这个功能是从这个html:启动的

<span id="hname">Name:</span><br> 
<input type="text" id="name" onblur="field_val('#hname', this);" 
    class="contact" name="name" size="31">

功能本身就在这里:

function field_val(label_id, input_id)
{
    var input_text = $(input_id).val();     
    var label_text = $(label_id).html();
    /* Considering surrounding the code in this function
        with an if statement that will not execute in the case
        that a submit button with an id of "fsubmit" has been
        pressed in conjunction with the onblur event that 
        called this function in the first place */
    if (input_text == "")
    {
        if(label_text.indexOf("(required field)") == -1)    
            $(label_id).html(label_text + " (required field)");
        $(label_id).css("color", "red");
    }
    else
    {
        if(label_text.indexOf("(required field)") != -1)    
            $(label_id).html(label_text.substring(0, label_text.indexOf("(required field)")));
        $(label_id).css("color", "rgb(51,51,51)");
    }
}

感谢您的帮助!

我想到的最简单的事情就是使用HTML5 required属性:

<input type="text" class="abc" id="id123" oninvalid="this.setCustomValidity('Required Field.')" onchange="this.setCustomValidity('')" required>

我正在将默认消息设置为显示"必填字段"。这在所有浏览器上都经过了尝试和测试。工作起来很有魅力。

并且,除非填写了所有required字段,否则不允许您提交表单。