django-formset icon indicating copy to clipboard operation
django-formset copied to clipboard

Submit form on enter

Open jdavid opened this issue 5 months ago • 4 comments

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();
        }
      }
    });
  });
});

jdavid avatar Aug 09 '25 11:08 jdavid

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?

jrief avatar Aug 09 '25 21:08 jrief

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.

jdavid avatar Aug 10 '25 14:08 jdavid

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.

jrief avatar Aug 10 '25 19:08 jrief

Thanks.

maybe adding a flag for explicitly enabling this

sounds good.

jdavid avatar Aug 11 '25 16:08 jdavid