Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Conditionally required form field (Checkbox)

I already checked multiple sites and posts regarding this topic, but couldn’t find an answer yet. I simply want to fire the following JS code if someone clicked a specific Checkbox in my form:

function updateRequirements() {
  var escortWrapper = document.querySelector(".elementor-field-type-html .elementor-field-group .elementor-column .elementor-field-group-field_ceffa28 .elementor-col-100");
  if (escortWrapper.style.display != 'none') {
    document.getElementById('escort').required = true;
  } else {
    document.getElementById('escort').required = false;
  }
}

You can check and test that for yourself on the following site:
Advelio Website

If you click on the second checkbox field, there is a field appearing where you can type in your name. And this field is currently optional, but I want to make this required if someone clicked the second checkbox.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

You can do it like this:

function updateRequirements() {
  const btn = document.getElementById('escort');
  btn.required = !btn.required;
}

document.querySelector("#requireCheck").addEventListener('click', updateRequirements);
<form>
  <input type="checkbox" id="requireCheck">
  <label for="requireCheck">Should the the other input be required?</label>
  <br>
  <input type="text" id="escort">
  <input type="submit" value="submit">
</form>

I simplified the function updateRequirements for the scope of this answer, but it can be changed to anything or any condition.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading