Svelte – each block – options for saving checkbox from input

In the documentation svelte did not find any suitable examples of working with checkbox in each blockthat would help my tasks. I had to come up with several of my own options.

Options for working with input type text in each block framework svelte you can learn from the article grouping and saving data in each block.

Option to save checkbox statuses on svelte

We receive data from the backend on which we will build the page.

<script>
import {onMount} from “svelte”;

let portfolio = [[];
onMount(async () => {
getFetch(‘portfolio / get-tracking-shares /’)then((r) => {portfolio = r});
});
script>

Add the function of sending data to the backend with a new status checkbox

<script>
function changeValue(e, share) {
let current = e.targetchecked;
getFetch(‘portfolio / save-share-tracking /’ + share.ticker + ‘/’ + checked);
}
script>

Then we throw the event into this function in this way:

on:change={(e) => changeValue(e, share)}

The fully formed data looks like this:

<div class=“table”>
<div class=“body”>
{#each portfolio as share}
<div class=“item”>
<div class=“cell name”>{share.name}</div>
<div class=“cell tracking”>
<label>
{#if share.tracking === true}
<input type=“checkbox” on: change={(e) => changeValue (e, share)} checked>
{: else}
<input type=“checkbox” on: change={(e) => changeValue (e, share)}>
{/ if}
</label>
</div>
</div>
{/ each}
</div>
</div>

It’s all! Our table in Svelte works great and sends new data on the status of the checkbox to the backend.

Alternative JS

We can do the same by adding a little more normal code. Js… We still use Svelte… However, we will catch the checkbox event by addEventListener

The example above is simpler, but this one is for hardcore.

In this case, the code inside the script would be like this:

<script>
onMount(async () => {
// Get the table ID
let table = document.getElementById(‘Portfolio’);

// Hang up the event on click using addEventListener
table.addEventListener(“click”, function (e) {
if (e.targetnodeName === ‘INPUT’) {
let current = e.target,
ticker = current.datasetticker,
checked = current.checked;
getFetch(‘portfolio / save-share-tracking /’ + ticker + ‘/’ + checked);
}
});
});
script>

The table itself will also change a little. Added here table id and date-attributes

<div class=“table” id=“Portfolio”>
<div class=“body”>
{#each portfolio as share}
<div class=“item”>
<div class=“cell tracking”>
<label>
{#if share.tracking === true}
<input type=“checkbox” data-ticker=“{share.ticker}” checked>
{: else}
<input type=“checkbox” data-ticker=“{share.ticker}”>
{/ if}
</label>
</div>
</div>
{/ each}
</div>
</div>

Similar Posts

Leave a Reply