Skip to content

Checkbox's onclick does not update own state #16689

@major-major-major-major

Description

Describe the bug

I want to derive the value of a checkbox from a state.

When an onclick handler (with preventDefault) changes its own checked state, it does not seem to be applied.

This seems like a bug.
If it is intended behavior, can anyone point out a reason or explanation?

The reason why I need the preventDefault() in my production use case is that I would like to only set the checked state if other conditions are met, not just as a direct consequence of the click.

<script>
	let on = $state(true);
	const toggle = () => {
		on = !on;
	}
</script>

<h1>Switches! on={on}</h1>

<label>
	<input
		checked={on}
		type=checkbox
		onclick={(evt) => {
			evt.preventDefault();
			toggle();
		}}
	>
	on
</label>
<br>
<button onclick={() => toggle()}>
	{on ? "on" : "off"}
</button>

Reproduction

Steps to reproduce the issue in the REPL:

  1. click on the checkbox
  2. observe that it changes the state in the header and button
  3. observe that it does not check the checkbox (whose value is derived from the same state)

https://svelte.dev/playground/hello-world?version=5.38.6#H4sIAAAAAAAACm1QPU_DMBD9K-6JIZVQI9aQBCExsDNiBie5tFaNHcWXtijKf-d8oZSBJXLe3fu6Gbz5RCjgFZ0L6hxG16kMO0vYbeEeeuswQvE-A30NaS8BjP-wnodhF0_oKGGNifgf3gZP6IlloIztaAeqtdfkkFTwqlJ3kQxhRuOE28c0YUIkRWG_d8jzbKuqWs1pokkYm-BlcdG-zG-Svjw81G9nS-0B44bFqzn4pcwZlakzDTrxLq0fJloVebk9Yie7K5KqVgI34XK1bZ1tj9Wc4Yn-5tHEwG4Y8cQVX7A3k6NsrSFSUuIXWMRBIoSUKL9GKptRvhOlhjc3sbqKLELknOpJaWABUEV69L0GOcVKr_nmhBeCIp10-eA_Y93Z-g6K3riIyzcfB0c29gEAAA==

Logs

System Info

see REPL URL:

Svelte `version=5.38.6`

reproducable without any special setup

Severity

annoyance

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions