How to disable the submit button of a Drupal form when it is clicked to prevent duplicate submission?

Sounds like a simple question. I added some jQuery magic:

$("#edit-save").click(function(event) { $(this).attr("disabled", "true"); }); 

However, once this is done, my form submit handler will not be called.

This is a custom form on my own path defined in hook_menu:

 $items['my_form'] = array( 'title' => 'My form', 'page callback' => 'drupal_get_form', 'page arguments' => array('mymod_myform'), 'type' => MENU_CALLBACK, ); 

In the form, I have a submit button and a cancel button:

 $form['cancel'] = array( '#type' => 'submit', '#value' => t('Cancel'), ); $form['save'] = array( '#type' => 'submit', '#value' => t('Save'), ); 

and I define my own submit handler:

 $form['#submit'][] = 'mymod_myform_submit'; 

I put some trace code in the drupal_get_form () function to sniff the $ _POST variable when submitting the form. When the jQuery mask is disabled, the $ _POST variable includes the "op" parameter:

 Array ( [op] = Save [form_build_id] => form-6e74c87390e3fc48d0bebd2f5193315b [form_token] => 33db6e34c0350e33c48861a63a38d45f [form_id] => dh_seo_workload_item_form ) 

but if I turn on jQuery magic to disable the submit button after it is pressed, the "op" parameter is no longer included in the $ _POST array, so Drupal believes that the form has not been submitted.

I saw a question in Prevent form submission in jQuery , but I am worried that this seems like a really hacky fix, and there should be a better way.

+4
source share
4 answers

Or you can do it as a single line addition at the level of an array of PHP forms ...

 $form['submit'] = array( '#type' => 'submit', '#value' => t('Save'), '#attributes' => array( 'onclick' => 'javascript:var s=this;setTimeout(function(){s.value="Saving...";s.disabled=true;},1);', ), ); 
+2
source

I think that the fact that you are attached to a button click event means that the button is disabled before the click event can go into the form and trigger the submit.

Our team found that disabling the submit button almost always creates problems for Internet Explorer. We made a tiny plugin to solve the problem; see code here: fooobar.com/questions/46852 / ...

+1
source

I set it this afternoon this way and was able to get the form information presented without problems:

 $("#id_of_button").click(function() { var submit = $(this); setTimeout(function(){ submit.attr('disabled','disabled') },1); }); 
0
source

Just hide the submit button ( display:none ) and show another button that is already disabled. I think it is less hacked than other solutions to this problem. Usually I have two buttons on my page, one visible and the other not, and onClick - just switch them.

The problem is that disabled buttons do not trigger postbacks.

0
source

Source: https://habr.com/ru/post/1332532/


All Articles