Submit form on enter
Because the fields are outside the <form> element, pressing the Enter key does not submit the form.
This is my workaround:
document.addEventListener('DOMContentLoaded', function() {
document.querySelectorAll('django-formset').forEach(formset => {
formset.addEventListener('keypress', function(event) {
if (event.key === 'Enter' && !event.shiftKey) {
event.preventDefault();
// Find the submit button and click it
const submitButton = formset.querySelector('button[type="submit"], input[type="submit"]');
if (submitButton) {
submitButton.click();
}
}
});
});
});
I get your point. But is this good practice? I mean, pressing Enter usually is also used to create a newline in a multiline editor. Something I could add is to invoke submit on Enter but only if no field has focus. How about that?
This is the latest version of my workaround, it handles the textarea case:
document.addEventListener('DOMContentLoaded', function() {
// Listen for keypress events on the document
document.addEventListener('keypress', function(event) {
const target = event.target;
if (event.key === 'Enter' && !event.shiftKey && target.tagName !== 'TEXTAREA') {
// Check if the event happened inside a django-formset
const formset = target.closest('django-formset');
if (formset) {
event.preventDefault();
const submitButton = formset.querySelector('button[type="submit"], input[type="submit"]');
if (submitButton) {
submitButton.click();
}
}
}
});
});
In a regular HTML form if an input element has the focus and the Enter key is pressed then the form is submitted, if no input has the focus then nothing happens. Invoking submit on Enter if no field has focus would actually depart from the expected behaviour.
Okay. I will change this in the code, maybe adding a flag for explicitly enabling this. Please wait until version 2.2 or 2.3 until it will be implemented.
Thanks.
maybe adding a flag for explicitly enabling this
sounds good.