Created
August 16, 2019 20:43
-
-
Save Samhamsam/ac955f204f726ae058c38dbabc9e80b9 to your computer and use it in GitHub Desktop.
Svelte Checkbox-Group, with parent and children checkboxes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<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