I am trying to add a placeholder for a select element and what I'm seeing when I add the selected
attribute for the first option there is just an empty space.
<select>
{#if placeholder}
<option value="" disabled selected>{placeholder}</option>
{/if}
{#each options as option}
<option value={option.value}>
{option.label || option.text}
</option>
{/each}
</select>
CodePudding user response:
The select initial value is different to the placeholder's empty string, that's why it is not selected by default. Make sure to bind the select value to a variable that match the placeholder at initialization like this:
<script>
let placeholder = 'hello world';
let options = [{
label: "Option 1",
value: "option1"
}, {
label: "Option 2",
value: "option2"
}, {
label: "Option 3",
value: "option3"
}];
let selectedValue = "";
</script>
<select bind:value={selectedValue}>
{#if placeholder}
<option value="" disabled selected>{placeholder}</option>
{/if}
{#each options as option}
<option value={option.value}>
{option.label || option.text}
</option>
{/each}
</select>
Working REPL: https://svelte.dev/repl/e1c7d9b804414f2d888b96b3e812a5c7?version=3.43.0