Kaspar L. Palgi
Kaspar L. Palgi

Reputation: 1502

How to set selected by default with HTML5 datalist

With HTML one can set the default selected item like this:

<option value="blaah" selected>

But how to do it with HTML5 and DataList select?

Upvotes: 4

Views: 2310

Answers (2)

Kaspar L. Palgi
Kaspar L. Palgi

Reputation: 1502

I had such a workaround that I added the default value into placeholder and then with the server-side language (I used PHP but you can do it with whatever you use) I check if the POST/GET is empty then it means default value.

Then I added into CSS:

::placeholder {  
    color: black; 
} 

So now it also looks right and doesn't give the user a feel that it's a placeholder and something needs to be done.

Upvotes: 4

Quentin
Quentin

Reputation: 943591

Not per se. Just set the value as normal.

<label for="ice-cream-choice">Choose a flavor:</label>
<input list="ice-cream-flavors" id="ice-cream-choice" name="ice-cream-choice" value="Strawberry" />

<datalist id="ice-cream-flavors">
    <option value="Chocolate">
    <option value="Coconut">
    <option value="Mint">
    <option value="Strawberry">
    <option value="Vanilla">
</datalist>

Of course, clicks in the input will be filtered by the text already there, so users will have to delete it to get the list of suggestions back.

Upvotes: 4

Related Questions