Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change style on losing focus with Js?

I want to perform validation on the input element once it loses focus and change the style of the element accordingly. I created the following code using internet. But it doesn't work(when the element loses focus the style doesn't get applied). What am I doing wrong ? / Any alternate methods ?

let inputTags = document.getElementsByTagName("input");
let validate = (event) => {
  let element = document.getElementById(event.target.id);
  element.style.border = "1px solid #ff0000 !important";
};
for (let i = 0; i < inputTags.length; i++) {
  inputTags[i].addEventListener("blur", validate);
}
<input type="text" id="a">
<input type="text" id="b">
<input type="text" id="c">
like image 878
Sushant Avatar asked Feb 03 '26 11:02

Sushant


1 Answers

border is a shorthand property. You can't have !important on it. You could have !important if you set borderWidth, borderColor, and borderStyle individually, but in general, avoid using !important.

Here it is without !important, but keep reading:

let inputTags = document.getElementsByTagName("input");
let validate = (event) => {
    let element = document.getElementById(event.target.id);
    element.style.border = "1px solid #ff0000";
};
for (let i = 0; i < inputTags.length; i++) {
    inputTags[i].addEventListener("blur", validate);
}
<input type="text" id="a">
<input type="text" id="b">
<input type="text" id="c">

A couple of notes about that code, though:

  1. You don't need let element = document.getElementById(event.target.id);, event.target is the input element. That said, I normally suggest using event.currentTarget because it's the element you hooked the handler on (whereas in general, event.target might be a child element, though of course not in this case, since the elements are input elements and so they can't have children).

  2. Rather than setting inline styles, I recommend using a class.

Here it is with those changes:

let inputTags = document.getElementsByTagName("input");
let validate = (event) => {
    event.currentTarget.classList.add("validated");
};
for (let i = 0; i < inputTags.length; i++) {
    inputTags[i].addEventListener("blur", validate);
}
.validated {
    border: 1px solid #ff0000;
}
<input type="text">
<input type="text">
<input type="text">

You might also look into using HTML validation and the :valid pseudo-class.

like image 168
T.J. Crowder Avatar answered Feb 04 '26 23:02

T.J. Crowder



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!