Kevin Renskers
Kevin Renskers

Reputation: 5950

Svelte: check a checkbox without forcing it to be checked

I have kind of an interesting problem with a Svelte app I'm building. In one of the forms I have a checkbox that I want to toggle on once a certain condition has been met, but I still want to allow the user to uncheck it manually.

<script>
    let number = 0;
    $: checked = checked || number >= 2;
</script>

<input type="number" bind:value={number}>
<label><input type="checkbox" bind:checked={checked}> Checkbox</label>

REPL

So once the number value is at least 2 the checkbox gets checked, but at that point it's impossible to uncheck it. What I want is that the "default value" gets changed to "checked" so to speak, but still allow the user to override. I hope my explanation makes sense!

How can I achieve this?

Upvotes: 2

Views: 2847

Answers (1)

Kevin Renskers
Kevin Renskers

Reputation: 5950

Okay, managed to find a solution myself:

<script>
    let number = 0;
    let checked = false;
    
    $: {
        checked = number >= 2;
    }
</script>

<input type="number" bind:value={number}>
<label><input type="checkbox" bind:checked={checked}> Checkbox</label>

This allows the checkbox to be checked/unchecked automatically based on the form values, but still allows the user to change the selection state manually.

Upvotes: 2

Related Questions