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.
There does not exist a placeholder attribute for the <select> tag. However, there are some ways of making a placeholder for the select box. The easiest way of making a placeholder for the <select> element is using the disabled and selected attributes with the HTML5 hidden global attribute.
To add a placeholder to a select tag, we can use the <option> element followed by the disabled , selected , and hidden attribute. The disabled attribute makes the option unable to select. The selected attribute shows the text inside <option> element opening and closing tags.
There is no attribute like input's placeholder for select box dropdown. However, you can create similar effect by using the HTML disabled and selected attribute on a <option> element that has empty value.
The placeholder attribute specifies a short hint that describes the expected value of an input field (e.g. a sample value or a short description of the expected format). The short hint is displayed in the input field before the user enters a value.
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>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With