Reputation: 1
I want to know if there is a way to add css on a required element in JavaScript I have many condition and i want it just in this case i want something like that (I know i can't do this) Thanks for your help !
if (!allAreFilled) { // While required element are empty
alert('Fill all the fields');
objForm.style:required.border = "solid 1px red"; // objForm = document.getElementById('compoundFormId')
}
Upvotes: 0
Views: 42
Reputation: 36512
You cannot directly change CSS style settings for pseudo elements or classes in Javascript.
But you can set CSS variables from JS.
This snippet sets a CSS variable --border
when the submit button is clicked with the value depending on a condition.
const button = document.querySelector('button');
let conditionIsSet = true;
button.addEventListener('click', function() {
document.body.style.setProperty('--border', (conditionIsSet) ? 'red' : 'black');
});
body {
--border: black;
}
input:required {
border: var(--border) 1px solid;
}
<input type="checkbox" onchange="conditionIsSet = !conditionIsSet;">Select condition is true</input>
<br> Input without required: <input> Input with required: <input required>
<button>Submit</button>
Obviously you need to supply whatever condition is needed.
Upvotes: 0