Home > Net >  Setting first (nth?) dropdown entry as default using array values
Setting first (nth?) dropdown entry as default using array values

Time:04-06

I have a dropdown that works well with simple values, but I just tried using arrays as values and now the initial dropdown-entry is empty.

I have created a REPL to illustrate the problem. As you can see I have also tried using selected=... to automatically select the first entry, but it doesn't work.

The only thing I can think of is to introduce another property to go back to simple values and then extract the array by filtering the original array, but it seems rather cumbersome. I wonder if there is another, more elegant, way that I'm missing.

Thank you in advance!

CodePudding user response:

Try this:

let currentFilter = availableFilters[0].key;

and you can remove selected={i === 0 ? 'selected' : ''} from the option.

See https://svelte.dev/tutorial/select-bindings

CodePudding user response:

Simply replace

let currentFilter = { key: ['filterAll'], value: "", code: 0 };

by

let currentFilter = availableFilters[0];

Even though the object has the exact same structure, it's still a different object that the one on the first position in the array. {} === {} // false The same applies to arrays.

['filterAll'] === ['filterAll'] // false
'filterAll' === 'filterAll' // true

currentFilter would have then this structure

{key: *bindedValue*, display: 'All Columns'}

If you want to extract the array you have to access the key when setting the initial value

let currentFilter = availableFilters[0].key;

and change the binding on the option

<select bind:value={currentFilter}>

REPL A Repl is great to have, but it would be better to include the code as well, in case the Repl might break...

  • Related