'Sveltekit how do I set checkboxes checked based on query params?
I am trying to set checkboxes active based on query parameters using Sveltekit. To achieve this, I tried to get all route query parameters using the 'url.searchParams.entries()' method to get all query parameters from the URL.
Then I am trying to loop through all the params and then loop through all posts and check if the value of the query param is equal to a value in posts. If so, it should set checked to true forEach checkbox that meets the value. Then in my HTML, I bind the checked variable to my checkbox. But the issue is that when I put in 4 in the query params (or select 4 using the checkbox), it checks all the checkboxes but, if I select any of the other checkboxes, it doesn't do a single thing (besides from querying data from the JSON placeholder api)
This is my HTML:
<div class="grid grid-cols-2">
{#each posts as post}
<div class="col-span-1">
<input type="checkbox" bind:checked={checked} value={post.id} bind:group=
{selectedPosts} on:change="{() => updateValue(post.id)}" class="mr-2">
</div>
<div class="col-span-1">
<label for="{post.id}">{post.id}</label>
</div>
{/each}
</div>
This is inside my script tag:
import { filter, results } from '../../stores.js';
import { page } from '$app/stores';
let checked = false
let selectedPosts = []
const posts = [
{
name: 'post',
id:'1'
},
{
name: 'post',
id: '2'
},
{
name: 'post',
id: '3'
},
{
name: 'post',
id: '4'
}
]
$: {
//If the query params would be '?posts=1', the output would be ['posts', '1']
let params = [...$page.url.searchParams.entries()]
params.forEach(param => {
//Returns the first param. In this case '1'
let value = param[1]
posts.forEach(post => {
if(post.id === value){
console.log('true')
checked = true
} else {
checked = false
console.log('false')
}
})
});
}
async function updateValue(value) {
filter.set(value)
}
In my store I set the query params like so:
export const results = derived(filter, (value) => {
if(!value) return {};
const data = fetch(`https://jsonplaceholder.typicode.com/todos/${value}`).then(res => {
return res.json()
})
return data
});
filter.subscribe(value => {
if(!value) return
goto(`/activiteiten/filter?post=${value.toString()}`)
return value
})
And finally I return with a derived store some data from the JSON placeholder API.
Solution 1:[1]
You don't need bind:checked={checked}
when using bind:group
. I think this is the root of your problem. You are setting the same checked
variable for every item.
if(post.id === value){
console.log('true')
checked = true
} else {
checked = false
console.log('false')
}
When you later check based on this variable, you get unexpected behavior.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Willem de Vries |