简体   繁体   English

使用JavaScript验证时,如果文本框内没有数据,则高亮显示红色

[英]Textbox Highlight red when no data inside it using javascript validation

I have a Text-box which highlights red when I click on it (on focus). 我有一个文本框,当我单击该框时,它会突出显示红色(焦点对准)。 If I type anything inside it it highlights back to grey. 如果我在其中键入任何内容,它将突出显示为灰色。 But When I type something inside it and again delete all the data inside it doesn't highlight back to red. 但是,当我在其中键入某些内容并再次删除其中的所有数据时,并不会突出显示为红色。 Please help me with it. 请帮我。 Here is the piece of code I used for highlighting it red and grey: 这是我用来突出显示红色和灰色的代码段:

$("#fname").bind('focus', function (e) {
    if ((document.getElementById("fname").value).length == 0) {
        document.getElementById("fname_error").style.display = "inline";
        $("#fname").attr('style', 'border: 1px solid #8C0005 !important;');

        return false;
    }
    else {
        document.getElementById("fname_error").style.display = "none";
    }
    return true;
});

$("#fname").keypress(function (e) {
    var iKeyCode = (e.which) ? e.which : e.keyCode


    if ((iKeyCode > 64 && iKeyCode < 91) || (iKeyCode > 96 && iKeyCode <      123) || iKeyCode==8 || iKeyCode == 9 ) {

                document.getElementById("fname_error").style.display = "none";
                $("#fname").attr('style', 'border: 1px solid #cccccc !important;');
                return true;

    }
    else {
            document.getElementById("fname_error").style.display = "inline";
            return false;
        }

});

That's because you are setting the red border inside focus event handler, and this event can not bi fired if the element is already focused. 那是因为您正在focus事件处理程序中设置红色边框,并且如果该元素已经被焦点,则此事件将不会被触发。

Try moving this code to keyup handler. 尝试将此代码移至keyup处理程序。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM