0

Is there a way to not count the default option as a submission in a required select element? For example if the default option is "Choose...", I don't want the user to be able to submit the form without changing this input. I want the user to have to choose one of the other options before they can submit.

isherwood
  • 58,414
  • 16
  • 114
  • 157
AKang123.
  • 405
  • 6
  • 15
  • Are you looking for something like this https://stackoverflow.com/a/30525521/9098350? – 5eb Jan 23 '21 at 17:03
  • Does this answer your question? [How can I set the default value for an HTML – aynber Aug 31 '22 at 18:01
  • While the above comments seem to answer a different question, I think this answer might be helpful, it uses JavaScript to prevent form submission unless an option is selected: https://stackoverflow.com/questions/24673989/how-to-prevent-form-submission-if-there-is-not-any-option-selected-from-dropdown – Bman70 Aug 31 '22 at 18:48

1 Answers1

1

The value of the default option is left empty (""), so the script can check and prevent form submission (event.preventDefault()) unless there is an option value.

Note the alert (popup) can be commented out or removed, and the form will still not submit until an option is selected. However, the user may not realize their mistake without some kind of notification.

function checkInput() {
  const choice = document.getElementById('cars');
  if (choice.value === '') {
    event.preventDefault();
    alert('Must select an option');
  }
}
select {
  width: 14rem;
  margin-bottom: 1em;
}
<form action="#" id="form">
  <select name="cars" id="cars">
    <option value="">Pick a Ride</option>
    <option value="volvo">Volvo</option>
    <option value="saab">Saab</option>
    <option value="mercedes">Mercedes</option>
    <option value="audi">Audi</option>
  </select>
  <br />
  <button type="submit" onclick="checkInput()">Submit Form</button>
</form>
isherwood
  • 58,414
  • 16
  • 114
  • 157
Bman70
  • 743
  • 5
  • 11
  • jQuery isn't tagged and comments are to be considered temporary. Your opening wasn't necessary, so I removed it. – isherwood Aug 31 '22 at 19:55