For the JS experts: How to prevent double form submission if form submits on change and the enter key is pressed


#1

Hi there,

this is more JS than ATK related:
I implemented a nice autosave, each input has an onChange handler that submits the form. This works perfectly for textareas and dropdowns, text inputs have one flaw:
When pressing the enter key in a text input, the form is submitted, too. Now this causes a double form submission as the enter key submits and the inChange handler submits. Any Idea how to stop this the smart way?

Thanks
Philipp


#2

can you show how you are doing on-change submit?


#3

Hi,

I have 2 versions:

  1. One Event handler for the whole form which delegates to the inputs

         $this->mainForm->on('change', 'input,textarea', $this->mainForm->js()->form('submit'));
    
  2. One for each input as I want to set some option to dropdowns anyway (I thought of using some other event handler, hence the double code for on(‘change’):

         foreach($this->mainForm->fields as $field) {
             $field->id = $field->short_name;
             $field->addClass('eoo-notification-border');
             if((new \ReflectionClass($field))->getShortName() == 'DropDown') {
                 $field->setDropdownOption('selectOnKeydown', false);
                 $field->on('change', $this->mainForm->js()->form('submit'));
             }
             else {
                 $field->on('change', $this->mainForm->js()->form('submit'));
             }
         }

#4

I thought of writing an own JS which does the following:

  1. serialize the value of each input and add it as data-serialized attribute (have that already to determine if a form field really changed).

  2. Add on focusOut event handler that checks if now the serialized value matches the previously one, if not (a change occured) submit form

  3. add onKeypress event handler that checks if enter key was pressed. If yes, submit if a change in input value (compare serialized values again) occured.

Thats the best Idea I came up so far.


#5

Just read that the submission on enter keypress is caused by Semantic UI… will try to investigate there…