Shantanu Gupta
Shantanu Gupta

Reputation: 21198

how to set border color of a texbox using jquery

How to set a default border color of a control using jquery.

       if (_userName.val().trim() == "") {
            errMsg += "\nUserName is a mandatory field.";
            _userName.css('border-color', 'red');
        }
        else {
            _userName.css('border-color', 'red');//Set border-color as loaded 
//when page was loaded
        }

How to Set border-color as loaded when page was loaded.

Upvotes: 7

Views: 50096

Answers (4)

Aamir Mahmood
Aamir Mahmood

Reputation: 2724

To set the color on page load you can do the following.

$(function(){
  $('#ID for _userName').css('border-color', color);
});

For border color as all other told, but it should be on form submission.

<form ... onSubmit="ValidateUser(this)">
... Your form elements ...
</form>

And your JS would look like this

function ValidateUser(frmObj){

    if (frmObj._userName.value.trim() == "") {
            errMsg += "\nUserName is a mandatory field.";
            $('#ID for _userName').css('border-color', color);
        }
        else {
            $('#ID for _userName').css('border-color', '');
        }
}

I will also suggest the same logic of creating a class same like Veera explained and to use that.

Upvotes: 2

Veera
Veera

Reputation: 33182

I would suggest creating a new style class called error and applying it on the textbox when the field contains error. Code snippet:

CSS: .error{border-color:#F00;}

        if (_userName.val().trim() == "") {
            errMsg += "\nUserName is a mandatory field.";
            $("#textboxid").addClass("error");
        }
        else {
            _userName.css('border-color', 'red');//Set border-color as loaded 
            $("#textboxid").removeClass("error");
        }

Advantage: If the field does not have any error, we can just remove the error class and the textbox look and feel will return to the original style. No need to track the original border color explicitly. And the style rule is re-usable too! ;-)

Upvotes: 5

Castrohenge
Castrohenge

Reputation: 8983

I'd give the html element being changed a css class that specifies color.

Just remove the border-color to reset it to the css class specified color:

_userName.css("border-color", "")

Upvotes: 0

Sarfraz
Sarfraz

Reputation: 382696

Get the border color at page load and store in a variable:

$(function(){
  var color = _userName.css('border-color');
});

And then you can use it later:

 if (_userName.val().trim() == "") {
        errMsg += "\nUserName is a mandatory field.";
        _userName.css('border-color', color);
    }
    else {
        _userName.css('border-color', color);
    }

Also make sure that there is a border at least eg border:1px solid #colorcode

Upvotes: 13

Related Questions