Home > front end >  Conditionally required form field (Checkbox)
Conditionally required form field (Checkbox)

Time:11-25

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.

CodePudding user response:

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.

CodePudding user response:

You have to have event listener for click event and if you dont have create one and wrote the function with logic what to do if is click

  • Related