Skip to content

Commit 4caf5de

Browse files
committed
feat(forms): easy form submit
1 parent 65f795f commit 4caf5de

File tree

2 files changed

+17
-5
lines changed

2 files changed

+17
-5
lines changed

packages/forms/src/components/WebForms.astro

Lines changed: 15 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -35,14 +35,25 @@ const clientScript = Astro.locals.forms.scriptToRun;
3535
<script>
3636
declare global {
3737
interface Window {
38-
__CSEvent: (event: KeyboardEvent, id: string) => void;
38+
__enterToSubmit: (event: KeyboardEvent, id: string) => void;
39+
submitForm(value: HTMLElement | string): void;
3940
}
4041
}
4142

42-
window.__CSEvent = function(event, id) {
43+
window.__enterToSubmit = function (event) {
4344
if (event.code === 'Enter') {
4445
event.preventDefault();
45-
document.getElementById(id)?.click();
46+
document.getElementById((event.target as HTMLElement).getAttribute('data-submit')!)?.click();
4647
}
47-
}
48+
};
49+
50+
window.submitForm = function (value: any) {
51+
if (typeof value !== 'string') {
52+
value = value.getAttribute('data-submit');
53+
}
54+
if(value == null){
55+
return console.warn('submitForm: value is null, make sure you pass `this` to this method or an id of the button you want to submit.');
56+
}
57+
document.getElementById(value)?.click();
58+
};
4859
</script>
Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,6 @@
11
export function addOnSubmitClickEvent(buttonId?: string | false, allProps?: {[key: string]: string}){
22
if(buttonId){
3-
allProps.onkeypress = `__CSEvent(event, '${buttonId}');${allProps.onkeypress ?? ''}`;
3+
allProps["data-submit"] = buttonId;
4+
allProps.onkeypress = `__enterToSubmit(event)${allProps.onkeypress ? ';' + allProps.onkeypress : ''}`;
45
}
56
}

0 commit comments

Comments
 (0)