Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make contenteditable="true" div have valid and invalid state

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?

like image 580
Roshan Budhathoki Avatar asked Jul 27 '18 05:07

Roshan Budhathoki


1 Answers

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>
like image 163
Reza Saadati Avatar answered Nov 15 '22 05:11

Reza Saadati