Skip to content

Commit 2e98ba8

Browse files
committed
feat: take form resets into account for two way bindings
When resetting a form, the value of the inputs within it get out of sync with the bound value of those inputs. This PR introduces a reset listener on the parent form to reset the value in that case closes #2659
1 parent fc6666b commit 2e98ba8

File tree

2 files changed

+33
-0
lines changed

2 files changed

+33
-0
lines changed

.changeset/silly-ways-wash.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+
feat: take form resets into account for two way bindings

packages/svelte/src/internal/client/render.js

Lines changed: 28 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1010,6 +1010,26 @@ export function selected(dom) {
10101010
});
10111011
}
10121012

1013+
/**
1014+
*
1015+
* @param {HTMLInputElement | HTMLSelectElement} element
1016+
* @param {(value: unknown) => void} update
1017+
*/
1018+
function listen_to_form_reset(element, update) {
1019+
// Inside effect to ensure the element is connected to the DOM
1020+
effect(() => {
1021+
const form = element.form;
1022+
if (form) {
1023+
const handler = () => {
1024+
// TODO defaultValue handling needs more thought
1025+
update(element.defaultValue || '');
1026+
};
1027+
form.addEventListener('reset', handler);
1028+
return () => form.removeEventListener('reset', handler);
1029+
}
1030+
});
1031+
}
1032+
10131033
/**
10141034
* @param {HTMLInputElement} dom
10151035
* @param {() => unknown} get_value
@@ -1056,6 +1076,8 @@ export function bind_value(dom, get_value, update) {
10561076

10571077
dom.value = stringify(value);
10581078
});
1079+
1080+
listen_to_form_reset(dom, update);
10591081
}
10601082

10611083
/**
@@ -1109,6 +1131,8 @@ export function bind_select_value(dom, get_value, update) {
11091131
dom.__value = value;
11101132
mounting = false;
11111133
});
1134+
1135+
listen_to_form_reset(dom, update);
11121136
}
11131137

11141138
/**
@@ -1210,6 +1234,8 @@ export function bind_group(group, group_index, dom, get_value, update) {
12101234
}
12111235
};
12121236
});
1237+
1238+
listen_to_form_reset(dom, update);
12131239
}
12141240

12151241
/**
@@ -1231,6 +1257,8 @@ export function bind_checked(dom, get_value, update) {
12311257
const value = get_value();
12321258
dom.checked = Boolean(value);
12331259
});
1260+
1261+
listen_to_form_reset(dom, update);
12341262
}
12351263

12361264
/**

0 commit comments

Comments
 (0)