computerR
computerR

Reputation: 11

Change input box style temporarly

I need to mark an input text box in red border while an error such as wrong email, wrong password etc. occurs if i do it in this way :

document.getElementById("loginFormEmail").style.borderColor = "red"

it stays red after, it changes the style perminantly, I need it to change back to its original color.

Upvotes: 0

Views: 86

Answers (3)

jeremy-denis
jeremy-denis

Reputation: 6878

In HTML5 you have a feature that allow you to do form validation

if you input is inside a form you can use attribute on input like pattern or type to make browser validate the input content on client side.

for sample on a mail address

<input type="email" id="email" pattern="[email protected]" required>

if you want an input with specific pattern

<input type="text" name="country_code" pattern="[A-Za-z]{3}" title="Three letter country code">

It will validate input and add css pseudo class valid and invalid that allow you to stylish your code

input:invalid {
  border: 1px solid red;
}

Upvotes: 1

kajgod
kajgod

Reputation: 11

You should add an event listener "change" to the element, and revert the color back.

Now, you COULD do it like this:

const elem = document.getElementById("loginFormEmail");
const oldColor =elem.style.borderColor; // remember old color
elem.style.borderColor = "red";
elem.addEventListener("change", ()=>{
  elem.style.borderColor = oldColor; // revert to the old color
});

BUT I would strongly advise you to create a "red" class in CSS, and append/remove it instead of setting the color inside JS.

Upvotes: 0

Webdeveloper_Jelle
Webdeveloper_Jelle

Reputation: 2856

You should make the input border red after an event started.
You can do:

if(error){  // your error checks
   document.getElementById("loginFormEmail").className += " error";
} else{
   document.getElementById("loginFormEmail").classList.remove("error");
}

and then in your CSS:

.error{
   border-color: red;
}

This will add the error class to your input that adds the red border and when there are no errors anymore it will remove the class which also removes the red border.

Upvotes: 0

Related Questions