简体   繁体   中英

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.

Try moving this code to keyup handler.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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