user3797088 user3797088 - 7 months ago 49
PHP Question

How set selected in a datalist HTML PHP

Greetings I would like to know if there is a way to set a selected value in a datalist. I would like something like this

<input list="cars" class="form-control" name="caBrands" style="width:300px;">
<datalist id="cars" >
<option selected="selected" value="BMW">
<option value="Toyota">
<option value="Mitsubishi">
</datalist>

Answer

The datalist is just an auto-complete list to be used with a textual input element. If you want to pre-set a value, just set the value of the input:

 <input list="cars" value="BMW" class="form-control" name="caBrands" style="width:300px;">
 <datalist id="cars">
 <option value="BMW">
 <option value="Toyota">
 <option value="Mitsubishi">

If you want to always select a value from a list, you can use a select element. This allows marking one option as selected, but it doesn't allow freeform input:

<select class="form-control" name="caBrands" style="width:300px;">
 <option selected value="BMW">BMW</option>
 <option value="Toyota">Toyota</option>
 <option value="Mitsubishi">Mitsubishi</option>
</select>

Comments