Skip to content

Commit

Permalink
feat(forms): easy form submit
Browse files Browse the repository at this point in the history
  • Loading branch information
ido-pluto committed Apr 29, 2024
1 parent 65f795f commit 4caf5de
Show file tree
Hide file tree
Showing 2 changed files with 17 additions and 5 deletions.
19 changes: 15 additions & 4 deletions packages/forms/src/components/WebForms.astro
Original file line number Diff line number Diff line change
Expand Up @@ -35,14 +35,25 @@ const clientScript = Astro.locals.forms.scriptToRun;
<script>
declare global {
interface Window {
__CSEvent: (event: KeyboardEvent, id: string) => void;
__enterToSubmit: (event: KeyboardEvent, id: string) => void;
submitForm(value: HTMLElement | string): void;
}
}

window.__CSEvent = function(event, id) {
window.__enterToSubmit = function (event) {
if (event.code === 'Enter') {
event.preventDefault();
document.getElementById(id)?.click();
document.getElementById((event.target as HTMLElement).getAttribute('data-submit')!)?.click();
}
}
};

window.submitForm = function (value: any) {
if (typeof value !== 'string') {
value = value.getAttribute('data-submit');
}
if(value == null){
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.');
}
document.getElementById(value)?.click();
};
</script>
3 changes: 2 additions & 1 deletion packages/forms/src/form-tools/events.ts
Original file line number Diff line number Diff line change
@@ -1,5 +1,6 @@
export function addOnSubmitClickEvent(buttonId?: string | false, allProps?: {[key: string]: string}){
if(buttonId){
allProps.onkeypress = `__CSEvent(event, '${buttonId}');${allProps.onkeypress ?? ''}`;
allProps["data-submit"] = buttonId;
allProps.onkeypress = `__enterToSubmit(event)${allProps.onkeypress ? ';' + allProps.onkeypress : ''}`;
}
}

0 comments on commit 4caf5de

Please sign in to comment.