the required attribute doesn't work on div with contentEditable ="true".Is there any way to make the field required so that div would have a valid and invalid state?
You could use the following script that allows you to use the required
attribute:
const selectors = document.querySelectorAll('div[contenteditable="true"][required]');
for (let selector of selectors) {
selector.addEventListener('input', () => {
if (selector.innerHTML === '') {
selector.style.border = '2px solid red';
selector.classList.add('content-invalid');
}
else {
selector.style.border = 0;
selector.classList.remove('content-invalid');
}
})
}
Assuming you have a form that should not be submitted if a value is missing:
const selectors = document.querySelectorAll('div[contenteditable="true"][required]');
for (let selector of selectors) {
selector.addEventListener('input', () => {
if (selector.innerHTML === '') {
selector.style.border = '2px solid red';
selector.classList.add('content-invalid');
}
else {
selector.style.border = 0;
selector.classList.remove('content-invalid');
}
})
}
document.querySelector('form').addEventListener('submit', (e) => {
if (document.querySelector('.content-invalid')) {
e.preventDefault();
}
})
<form action="">
<div contenteditable="true" required>Hello</div>
<div contenteditable="true" required>World</div>
<input type="submit">
</form>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With