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 ?
<script>
let inputTags = document.getElementsByTagName("input");
let validate = (event) => {
console.log(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);
}
</script>
>Solution :
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:
-
You don’t need
let element = document.getElementById(event.target.id);,event.targetis theinputelement. That said, I normally suggest usingevent.currentTargetbecause it’s the element you hooked the handler on (whereas in general,event.targetmight be a child element, though of course not in this case, since the elements areinputelements and so they can’t have children). -
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.