user3835327
user3835327

Reputation: 1204

onBlur change textbox background color

How can i change my textbox background and border color if return true from the function ? if return false my textbox background border will change, but when return true it remain red color. how can i fix this ? any help will be appreciated.

Javascript

function checkPostcode() 
{

    var message = "";

    if (document.mainform.POSTCODE.value.length != 5)
    {
        message += "Invalid entry. Postcode must be in 5 number.";
    }
    else
    {
        for (var i = 0; i < document.mainform.POSTCODE.value.length; i++)
        {
            var f = document.mainform.POSTCODE.value.charAt(i);
            if (!(parseFloat(f) >= 0) || !(parseFloat(f) <= 9))
            {
                var jdap = "no";
            }
        }

        if (jdap=="no")
        {
            message += "Invalid entry. Please enter numbers only.";
        }
    }

    if (message != "") 
    {
            document.getElementById("posterrMsg").innerHTML      = message;
            document.getElementById("posterrMsg").style.display  = "inline";
            document.getElementById("POSTCODE").style.border     = "thin solid red";
            document.getElementById("POSTCODE").style.background = "#FFCECE";
            document.mainform.POSTCODE.value = "";
            document.mainform.POSTCODE.focus();
            return false;
    }
    else{

            document.getElementById("posterrMsg").innerHTML         = "";
            document.getElementById("posterrMsg").style.display     = "";
            document.getElementById("POSTCODE").style.border        = "thin solid #CCCCCCC";
            document.getElementById("POSTCODE").style.background    = "FFFFFF";
        return true;
    }

}

HTML

 <label id="posterrMsg" class="errMsg"></label> 
 <input type="text" name="POSTCODE" id="POSTCODE" value="<%=POSTCODE%>" onblur="checkPostcode();" maxlength="5" />

Upvotes: 1

Views: 1912

Answers (3)

obaylis
obaylis

Reputation: 3034

Use !== so

if (message !== "") 

so that you are checking the same type and value.

You also had a couple of typeos in your background colours.

See working JSFiddle here

Upvotes: 0

magnudae
magnudae

Reputation: 1272

Another option:

document.getElementById("POSTCODE").className = "validPostcode";

or

document.getElementById("POSTCODE").className = "invalidPostcode";

If you want to add more styling.

Both are valid options here.

I would refactor your code a bit and maybe create an outer function which calls checkPostcode for validation.

Upvotes: 0

Chop
Chop

Reputation: 534

Just change

document.getElementById("POSTCODE").style.border = "thin solid #CCCCCCC";

to

document.getElementById("POSTCODE").style.border = "";

Upvotes: 1

Related Questions