Skip to content

Commit 012166e

Browse files
fix: convert input value to number on hydration (#14349)
* convert input value to number on hydration * add test * changeset --------- Co-authored-by: Rich Harris <[email protected]>
1 parent b145035 commit 012166e

File tree

4 files changed

+29
-1
lines changed

4 files changed

+29
-1
lines changed

.changeset/wicked-grapes-flash.md

Lines changed: 5 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,5 @@
1+
---
2+
'svelte': patch
3+
---
4+
5+
fix: coerce value to number when hydrating range/number input with changed value

packages/svelte/src/internal/client/dom/elements/bindings/input.js

Lines changed: 1 addition & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -45,7 +45,7 @@ export function bind_value(input, get, set = get) {
4545
// If we are hydrating and the value has since changed, then use the update value
4646
// from the input instead.
4747
if (hydrating && input.defaultValue !== input.value) {
48-
set(input.value);
48+
set(is_numberlike_input(input) ? to_number(input.value) : input.value);
4949
return;
5050
}
5151

Lines changed: 17 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
import { flushSync } from 'svelte';
2+
import { test } from '../../test';
3+
4+
export default test({
5+
skip_mode: ['client'],
6+
7+
test({ assert, target, hydrate }) {
8+
const input = /** @type {HTMLInputElement} */ (target.querySelector('input'));
9+
input.value = '1';
10+
input.dispatchEvent(new window.Event('input'));
11+
// Hydration shouldn't reset the value to empty
12+
hydrate();
13+
flushSync();
14+
15+
assert.htmlEqual(target.innerHTML, '<input type="number">\n1 (number)');
16+
}
17+
});
Lines changed: 6 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,6 @@
1+
<script>
2+
let value = $state(0);
3+
</script>
4+
5+
<input type="number" bind:value={value}>
6+
{value} ({typeof value})

0 commit comments

Comments
 (0)