10

So heres my code at this moment in time (Note - this code is inside of a PHP for loop being echo'd out, so when you see the $i variable just assume its a number that's incrementing every pass):

<select name='field{$i}type' class='form-control' required>
    <option disabled selected hidden>Type of Field</option>
    <option value='text'>Text</option>
</select>

When this select is created dynamically with my php, I want to have a "placeholder" for the select. I've found answers on how to make the placeholder (Bootstrap select dropdown list placeholder), which is now there and working. However, i need this select to be required. I need to force the user to select the text option before form submission. Any way to do this in pure HTML? the required option is getting confused i believe because i've put in the "selected" parameter. Is that the case? How can I fix this.

J. Robinson
  • 931
  • 4
  • 17
  • 45

1 Answers1

25

If the value is null like value="" and it is required, then you need a value to submit (HTML validation.)

The required attribute

The simplest HTML5 validation feature to use is the required attribute — if you want to make an input mandatory, you can mark the element using this attribute. When this attribute is set, the form won't submit (and will display an error message) when the input is empty (the input will also be considered invalid).

REF: https://developer.mozilla.org/en-US/docs/Learn/HTML/Forms/Form_validation

<form>
  <select name='field{$i}type' class='form-control' required>
    <option disabled value="" selected hidden>Type of Field</option>
    <option value='text'>Text</option>
</select>

  <button type="submit">SUBMIT</button>
</form>
Community
  • 1
  • 1
Dalin Huang
  • 11,212
  • 5
  • 32
  • 49