Search code examples
javascriptsveltekit

Toggle a checkbox when the row it is in is clicked in Svelte


I have this checkbox inside a table row and the row has a click event, what I am trying to do is to toggle the checkbox when the whole row is clicked, the event is firing and the field is being updated when I use console.log inside the toggle function. but the displayed value does not change and the checkbox is not being toggled:

let items = [ 
{  "id": 1,
   "name": "Item1",
   "selected": false
},
{  "id": 2,
   "name": "Item2",
   "selected": false
}]

const toggle = (item) => {
    item.selected = !item.selected
}

...
{#each items as item, index(item['id'])}
    <tr on:click={()=>toggle(item)}>
        <td>
            <input type=checkbox bind:checked={item['selected']}/>
        </td>
    </tr>
{/each}

Solution

  • The reason for the update not working is because you are changing a property of the object that is bound but not the object reference itself. In order to make it that it triggers an update you need to re-assign the item in your toggle function like this:

    <script>
    let items = [ 
      { "id":1,
        "name":"Item1",
        "selected":false
      },
      { "id":2,
        "name":"Item2",
        "selected":false
      }
    ]
    
    const toggle = (item, index) => {
        item.selected = !item.selected
        items[index] = item;
    }
    </script>
    
    <table>
    {#each items as item, index}
        <tr on:click={()=>toggle(item, index)}>
            <td style="background: red; width: 50px;">
                <input type=checkbox bind:checked={item['selected']}/>
            </td>
        </tr>
    {/each}
    </table>
    

    Note that I added some background color and width to make this more visible.