munmun poddar
munmun poddar

Reputation: 107

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

});

Upvotes: 0

Views: 97

Answers (1)

k102
k102

Reputation: 8079

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.

Upvotes: 0

Related Questions