How to set texbox border color using jquery

How to set the 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 the border color as loaded when the page loads.

+6
javascript jquery css
source share
4 answers

Get the border color when loading the page and save 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 there is a border, for example border:1px solid #colorcode

+10
source share

I would suggest creating a new style class called error and apply it in the text field when the field contains an 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 there is no error in the field, we can simply delete the error class, and the appearance of the text field will return to the original style. No need to explicitly track the original border color. And the style rule can be used again !; -)

+5
source share

To set the color when loading the page, you can do the following.

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

For the color of the border, like everyone else, but it must be presented in shape.

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

And your JS will 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 also suggest the same class creation logic as Veera, and use that.

+2
source share

I would give an html element that was modified by the css class that indicates the color.

Just strip border-color to reset to the css class indicated by color:

 _userName.css("border-color", "") 
0
source share

All Articles