Skip to content

Instantly share code, notes, and snippets.

@Samhamsam
Created August 16, 2019 20:43
Show Gist options
  • Save Samhamsam/ac955f204f726ae058c38dbabc9e80b9 to your computer and use it in GitHub Desktop.
Save Samhamsam/ac955f204f726ae058c38dbabc9e80b9 to your computer and use it in GitHub Desktop.
Svelte Checkbox-Group, with parent and children checkboxes
<script>
export let name;
let filling = [];
let parent_check = [];
let data = [
{
ranchname: "test",
groups: ["a", "b", "c", "d", "e"]
},
{
ranchname: "test2",
groups: ["a2", "b2", "c2", "d2"]
}
];
function parent_checkbox_check() {
let found = data.find(e => {
return e.ranchname === event.target.value;
});
const input_checked = event.target.checked;
if (input_checked) {
filling = [...found.groups];
} else {
filling = filling.filter(e => {
return !found.groups.includes(e);
});
}
}
function child_checkbox_check() {
const parent_name = event.target.getAttribute("parent");
let found = data.find(e => {
return e.ranchname === parent_name;
});
let count = 0;
found.groups.forEach(e => {
if (filling.includes(e)) {
count++;
}
});
if (event.target.checked) {
count++;
} else {
count--;
}
if (count === found.groups.length) {
parent_check[parent_name] = true;
} else {
parent_check[parent_name] = false;
}
}
</script>
<style>
h1 {
color: purple;
font-size: 4rem;
}
</style>
{#each data as item}
<input
type="checkbox"
value={item.ranchname}
bind:checked={parent_check[item.ranchname]}
on:click={parent_checkbox_check} />
{item.ranchname}
<div>
{#each item.groups as itemg}
<input
on:click={child_checkbox_check}
bind:group={filling}
type="checkbox"
parent={item.ranchname}
value={itemg} />
{itemg}
{/each}
</div>
{/each}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment