簡體   English   中英

使用JavaScript驗證時,如果文本框內沒有數據,則高亮顯示紅色

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

我有一個文本框,當我單擊該框時,它會突出顯示紅色(焦點對准)。 如果我在其中鍵入任何內容,它將突出顯示為灰色。 但是,當我在其中鍵入某些內容並再次刪除其中的所有數據時,並不會突出顯示為紅色。 請幫我。 這是我用來突出顯示紅色和灰色的代碼段:

$("#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;
        }

});

那是因為您正在focus事件處理程序中設置紅色邊框,並且如果該元素已經被焦點,則此事件將不會被觸發。

嘗試將此代碼移至keyup處理程序。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM