1

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.

mayo09876
  • 21
  • 5
  • If you want the two to be selectable at the same time you should take a look at the [submit](https://developer.mozilla.org/fr/docs/Web/API/HTMLFormElement/submit_event) event to validate your form, or else use a required radio button as suggested – Kaddath Jun 19 '23 at 17:03

2 Answers2

0
  • 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>
zer00ne
  • 41,936
  • 6
  • 41
  • 68
0

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>
Alexander Nenashev
  • 8,775
  • 2
  • 6
  • 17