skip to Main Content

Part of my HTML form looks like this:

<p>Please select your preferred time slot:</p>
<input type="checkbox" id="am" name="am" value="AM">
<label for="am">AM (09:00-13:00)</label><br>
<input type="checkbox" id="pm" name="pm" value="PM">
<label for="pm">PM (13:00-18:00)</label><br>

I’d like for at least one of the checkboxes to be selected as a requirement of the form being submitted. I’d also like the option of both boxes being ticked at the same time. At the moment, if I leave both unselected, the form is still submitted.

I considered using the required property but I can’t figure out how to utilise it without making both required.

2

Answers


    • Change the type from "checkbox" to "radio"
    • all radio buttons must share a common [name] value (ex. all are name="m")
    • then add required to only one of them.
    • add another radio button with both values or something that represents both AM and PM slots.
    <form>
      <fieldset style="width: max-content">
        <legend>Please select your preferred time slot:</legend>
        <input id="am" name="m" type="radio" value="AM" required>
        <label for="am">AM (09:00-13:00)</label><br>
        <input id="pm" name="m" type="radio" value="PM">
        <label for="pm">PM (13:00-18:00)</label><br>
        <input id="ap" name="m" type="radio" value="AP">
        <label for="ap">AM/PM (09:00-18:00)</label><br>
        <button style="font: inherit; float: right;">Done</button>
      </fieldset>
    </form>
    Login or Signup to reply.
  1. Just check on input whether any of the checkboxes is selected. If not – reselect the changed checkbox:

    const checkboxes = document.querySelectorAll('input[type=checkbox]');
    
    setValidity();
    
    checkboxes.forEach(checkbox => checkbox.addEventListener('input', e => {
      [...checkboxes].some(checkbox => checkbox.checked) || (e.target.checked = true)
      setValidity();
    }));
    
    function setValidity(){
      const validity = 
      [...checkboxes].some(checkbox => checkbox.checked) ? '' : 'The time slot is required';
      [...checkboxes].at(-1).setCustomValidity(validity);
    }
    <form>
    <p>Please select your preferred time slot:</p>
    <input type="checkbox" id="am" name="am" value="AM">
    <label for="am">AM (09:00-13:00)</label><br>
    <input type="checkbox" id="pm" name="pm" value="PM">
    <label for="pm">PM (13:00-18:00)</label><br><br>
    <button>Submit</button>
    </form>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search