Svelte – how to make dropdown in each block

There are examples of a drop-down list on the official website, but if you try to repeat the same for each-block, then choosing a menu item from the drop-down list for one item, the action will be repeated in all the others. I’ll tell you how to avoid it and do it right.

In order to avoid repetition, you need to transfer inward value for each element its own variable.

But how do we know how many elements we will have? Can’t create a separate variable for each element like in the docs?

We will use the creation of a variable from the same data array each block that we are iterating from. Namely, we will refer to the nonexistent key (el.value), thus creating one for each item.

Now it doesn’t matter how many elements there are inside the array elements, each field will be unique. And when you select a certain value from the menu list, only this value and only for this field will be sent to the processing function changeElement (el.id, el.value)

It looks like this:

{#each elements as el}
<div class=“cell select-block”>
<form class=“select-block” on:change={() => changeElement(el.id, el.value)}>
<label>
<select bind:value={el.value}>
<option value=“” selected disabled hidden>Select valueoption>

<option value=‘paragraph 1’>paragraph 1option>
<option value=‘point 2’>paragraph 2option>
select>
label>
form>
div>
{/each}

And inside the function, we process the passed values ​​at our discretion. For example, you can pass these values ​​to the backend for changes in the database.

An example of how it might look:

function changeElement(id, value) {
let yes = confirm(“Do you want to change” + “‘” + value + “‘” + “?”);

if (!yes) {
return;
}

let data = {
‘id’: id,
‘value’: value
}

postFetch(‘change-value /’, data)then((r) => {
if (r === ‘ok’) {

}
});
}

Then it remains to process it on the backend.

Similar Posts

Leave a Reply

Your email address will not be published. Required fields are marked *