Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Change text input border color

I want to make a form where data is verified using JavaScript before being sent. When a field is empty, I want to set its border to red.

HTML code:

<label>Question: </label><input type = "text" maxlength = "100" name = "question"> <br />

JavaScript code 1:

fields[i].style.borderColor = "red";

JavaScript code 2:

fields[i].style.border = "1px solid red";

If I use JS code 1, the border changes its color but it has the width bigger than before (even though I do not say anything about border width). If I use JS code 2, the text input shrinks with 2px and the change is noticeable.

What should I do to change only the border color?

like image 484
Sorin Avatar asked Apr 16 '26 00:04

Sorin


1 Answers

Actually this is preferred by adding and removing classes:

$("input").change(function()
  {
     var value = $(this).val();
     if(value=="")
     {
          $(this).addClass("red-border");
          $(this).focus();
     }else
     {
          $(this).removeClass("red-border");
     }
  });

And your CSS:

.red-border{
    border: 1px solid red;
}
like image 169
Gaurav Bhor Avatar answered Apr 18 '26 14:04

Gaurav Bhor