21
<select name="status" required>
<option selected disabled>status</option>

I have set required attribute in html select.

My first option set selected disabled for display text.

However it will cause required attribute not working.

anyone know how to solve this problem?

Benjamin W
  • 2,658
  • 7
  • 26
  • 48

2 Answers2

50

Set <option>'s value to empty string ('').

Updated Code

<select name="status" required>
    <option selected disabled value="">status</option>
    <!-- Additional options here (at least one should not be disabled) -->
</select>

Explanation

select will return the value of the selected option to the server when the user presses submit on the form. An empty value is the same as an empty text input → raising the required message.


More info (w3schools)

The value attribute specifies the value to be sent to a server when a form is submitted.

Example

document.querySelector('form').onsubmit = (e) => {
  e.preventDefault();
  const status = e.target[0].value;
  console.log(`Your status is: "${status}"`);
 }
<form>
  <select name="status" required>
    <option selected disabled value="">Select a status...</option>
    <option value="Good">Good</option>
    <option value="Bad">Bad</option>
   </select>
   <input type="submit" value="Submit">
 </form>
JBallin
  • 8,481
  • 4
  • 46
  • 51
0

To step one further: The problem with the disabled attribute on the selected option element is that the container <select> element will also treated as disabled, and this leads to this select element's value will not being posted to the server at all, and JavaScript new FormData() constructor also omit it.

To solve this, change the disabled to readonly. And add the hidden attribute also, so the selected option will not appear in the dropdown menu. With setting it's value to "" (falsy), the input validator prevents form submitting with a validation report, even without JavaScript. This solution also solves the problem of the FormData constructor and you will also be able to easily find that this input has an invalid value with the Constraint Validation API's selectElement.checkValidity() method.

<form>
  <select name="status" required>
    <option value="" hidden readonly selected>I am a placeholder...</option>
    <option value="Good">Good</option>
    <option value="Bad">Bad</option>
   </select>
   <input type="submit" value="Submit">
</form>