20
<input type="submit" name="btnADD" id="btnADD" value="ADD"/>

when user click add button twice, from get submitted twice with same data into table. So Please help me to restrict user to submit from twice.

  • In general you could add some database restrictions or something that will guarantee that nothing wrong will happen in either case. – quazar Jul 09 '18 at 13:05

16 Answers16

33

Once the form is submitted, attach a handler with jQuery that hijacks and "disables" the submit handler:

var $myForm = $("#my_form");
$myForm.submit(function(){
    $myForm.submit(function(){
        return false;
    });
});

Returning "false" from the submit handler will prevent the form from submitting. Disabling buttons can have weird effects on how the form is handled. This approach seems to basically lack side effects and works even on forms that have multiple submit buttons.

rogueleaderr
  • 4,671
  • 2
  • 33
  • 40
  • 1
    Seems the best solution because if you disable the submit button before the post is sent, you wont be able to verify submit button's value as it won't be send... – Axi Dec 12 '14 at 10:15
  • 1
    Very good. For usability's sake it might be a good idea to let this handler also change the button(s) appearance (disable or otherwise make it clear to the user that 'Computer will now say no, waitaminute..') – st3inn Jan 15 '15 at 09:41
  • 2
    Small gripe with this is that every time the user hits the button you'll be adding another event handler. This won't cause any issues, but some people may not want that. A simple fix is to simply remove any "submit" handlers on the form before adding the new one. – Hayley Jan 06 '16 at 11:33
  • Could someone please do a JSFiddle or something that proves that this works? – nmit026 Sep 28 '16 at 22:18
  • 1
    It works, but as-is it will also disable the button if validation fails and the form is not submitted – in my case, anyway. – Toadfish Oct 10 '16 at 03:38
  • @JonathanWarner if you have validation, you probably want to attach the submit handler only after the validation succeeds, instead of on form submit (or do the validation on the form submit and only attach the handler if it succeeds). – rogueleaderr Oct 10 '16 at 18:15
  • Yep, i just needed to add `if ($form.valid())` and it worked perfectly. – Toadfish Oct 11 '16 at 03:11
  • 1
    Nice answer but please tell us what are the weird side effects of disabling the submit button? – ADTC Dec 08 '16 at 18:05
  • It seems like this works when the user presses the back button too! Thanks! – Josh Sep 18 '20 at 16:04
25

try out this code..

<input type="submit" name="btnADD" id="btnADD" value="ADD" onclick="this.disabled=true;this.value='Sending, please wait...';this.form.submit();" />
Vijay
  • 8,131
  • 11
  • 43
  • 69
  • 9
    Wouldn't this still submit the from if a user presses enter on a field? – Ziyan Junaideen Jul 24 '14 at 13:01
  • @Ziyan, using would do the trick with Vijay's Answer :) – Rakesh Shewale Dec 25 '14 at 09:39
  • Also user can enable the button again by editing code through browser(Inspect Element) – foxt7ot Apr 14 '15 at 12:05
  • 1
    What if the inputs are incorrect ? Like if the user entered a negative value in a number input with attribute min=0 ? The button will be disabled and the user will not be able to re-click on it after having corrected his inputs, right ? – pawamoy Apr 26 '16 at 12:25
  • 4
    @foxt7ot if a user is that savvy, he will find a way to double-post no matter what javascript you do to prevent it. only server-side duplicate checking can truly prevent it. – ADTC Dec 08 '16 at 18:08
  • @ADTC Oh yes! Indeed – foxt7ot Dec 09 '16 at 05:13
7

You can disable the button after clicking or hide it.

<input type="submit" name="btnADD" id="btnADD" value="ADD" onclick="disableButton(this)"/>

js :

 function disableButton(button) {
     button.disabled = true;
     button.value = "submitting...."
     button.form.submit();
}
mlwacosmos
  • 4,391
  • 16
  • 66
  • 114
4

If you are working with java server side scripting and also using struts 2 then you refer this link which talks about on using token.

http://www.xinotes.org/notes/note/369/

A token should be generated and kept in session for the initial page render, when the request is submitted along with the token for the first time , in struts action run a thread with thread name as the token id and run the logic whatever the client has requested for , when client submit again the same request, check whether the thread is still running(thread.getcurrentthread().interrupted) if still running then send a client redirect 503.

And if you are not using any framework and looking for simple workout. You can take help of the

java.util.UUID.randomUUID();

Just put the random uuid in session and also in hidden form field and at other side(the jsp page where you are handling other work like storing data into database etc.) take out the uuid from session and hidden form field, If form field matches than proceed further, remove uuid from session and if not than it might be possible that the form has been resubmitted.

For your help i am writing some code snippet to give idea about how to achieve the thing.

<%
String formId=(java.util.UUID.randomUUID()).toString();
session.setAttribute(formId,formId);
%>
<input type='hidden' id='formId' name='formId' value='<%=formId%>'>
foxt7ot
  • 2,465
  • 1
  • 19
  • 30
  • http://www.xinotes.org/notes/note/369/ The link that you shared, if I use this method it is possible that the second request gets entertained and first gets cancelled. Am I right? – Sunny Gupta Mar 17 '15 at 17:36
3

You could notify the user that he drinks too much coffee but the best is to disabled the button with javascript, for example like so:

$("#btnADD").on('click', function(btn) {
  btn.disabled = true;
});
11684
  • 7,356
  • 12
  • 48
  • 71
scraaappy
  • 2,830
  • 2
  • 19
  • 29
  • Heh. I just had this exact problem, someone submitted the same form 11 times! On testing It turned out they have a fast trigger finger. Which in turn led me to here...:D – Chud37 Mar 14 '14 at 09:54
2

I made a solution based on rogueleaderr's answer:

jQuery('form').submit(function(){
    jQuery(this).unbind('submit'); // unbind this submit handler first and ...
    jQuery(this).submit(function(){ // added the new submit handler (that does nothing)
        return false;
    });
    console.log('submitting form'); // only for testing purposes
});
André Sousa
  • 428
  • 5
  • 9
2

My solution for a similar issue was to create a separate, hidden, submit button. It works like so:

  • You click the first, visible button.
  • The first button is disabled.
  • The onclick causes the second submit button to be pressed.
  • The form is submitted.
<input type="submit" value="Email" onclick="this.disabled=true; this.value='Emailing...'; document.getElementById('submit-button').click();">
<input type="submit" id='submit-button' value="Email" name="btnSubmitSendCertificate" style='display:none;'>

I went this route just for clarity for others working on the code. There are other solutions that may be subjectively better.

Daniel Beck
  • 20,653
  • 5
  • 38
  • 53
Bryant Makes Programs
  • 1,493
  • 2
  • 17
  • 39
1

When user click on submit button disable that button.

<form onSubmit="disable()"></form>

function disable()
{
     document.getElementById('submitBtn').disabled = true;
    //SUBMIT HERE
}
PSR
  • 39,804
  • 41
  • 111
  • 151
  • **+1** It's good idea to write the code completely, and make a jsFiddle too `;)`. –  May 29 '13 at 12:47
  • 1
    I've been using this technique, but I just ran into an issue with it. Disabled inputs aren't sent to the server, and when I changed the server script to test `$_POST['submitBtn']` (because I added multiple submit buttons and needed to know which they used) it failed because it wasn't set. – Barmar Feb 10 '15 at 17:02
  • @Barmar you can either hide the button(s) or (if you need to keep the button visible), place a div on top of the button(s) so that it cannot be clicked. That way the button is not disabled, and is sent with the form data. – ADTC Dec 08 '16 at 18:12
  • Just disabling the button on a form isn't enough, it prevents the form to be submitted. – Kevin D. Jan 23 '23 at 09:51
1

You can use JavaScript.

Attach form.submit.disabled = true; to the onsubmit event of the form.

A savvy user can circumvent it, but it should prevent 99% of users from submitting twice.

shauneba
  • 2,122
  • 2
  • 22
  • 32
1

You can display successful message using a pop up with OK button when click OK redirect to somewhere else

smk
  • 351
  • 2
  • 4
  • 14
1

Disable the Submit Button

$('#btnADD').attr('disabled','disabled');

      or

$('#btnADD').attr('disabled','true');
Janak
  • 4,986
  • 4
  • 27
  • 45
1

Create a class for the form, in my case I used: _submitlock

$(document).ready(function () {
  $(document).on('submit', '._submitlock', function (event) {

      // Check if the form has already been submitted
      if (!$(this).hasClass('_submitted')) {
          // Mark the form as submitted
          $(this).addClass('_submitted');

          // Update the attributes of the submit buttons
          $(this).find('[type="submit"]').attr('disabled', 'disabled');
          // Add classes required to visually change the state of the button
          $(this).find('[type="submit"]').addClass("buttoninactive");
          $(this).find('[type="submit"]').removeClass("buttonactive");

      } else {
          // Prevent the submit from occurring.
          event.preventDefault();
      }

  });});
Campinho
  • 432
  • 5
  • 13
1

Put a class on all your buttons type="submit" like for example "button-disable-onsubmit" and use jQuery script like the following:

$(function(){
    $(".button-disable-onsubmit").click(function(){
         $(this).attr("disabled", "disabled");
         $(this).closest("form").submit();
    });
});

Remember to keep this code on a generic javascript file so you can use it in many pages. Like this, it becomes an elegant and easy-to-reuse solution. Additionally you can even add another line to change the text value as well:

$(this).val("Sending, please wait.");
Daniel Almeida
  • 342
  • 2
  • 4
  • The second line; "$(this).closest("form").submit();" makes sure the form actually get's submitted. Just adding the attribute 'disabled' to the button doesn't cut it. – Kevin D. Jan 23 '23 at 09:50
1

Add a class to the form when submitted, stopping a user double clicking/submitting

$('form[method=post]').each(function(){
   $(this).submit(function(form_submission) {
     if($(form_submission.target).attr('data-submitted')){
        form_submission.preventDefault();
     }else{
        $(form_submission.target).attr('data-submitted', true);
     }
  });
});
Planty
  • 85
  • 1
  • 12
0

You can add a class to your form and your submit button and use jquery:

$(function() {

    // prevent the submit button to be pressed twice
    $(".createForm").submit(function() {
        $(this).find('.submit').attr('disabled', true);
        $(this).find('.submit').text('Sending, please wait...');
    });
})
FelipeOliveira
  • 759
  • 8
  • 21
  • 1
    There's really no need to add classes `$(this).find('[type=submit]')` would surely achieve the same without the need to add any classes. – FireLeopard Feb 26 '19 at 10:12
0

None of these solutions worked for me as my form is a chat and repeated submits are also required. However I'm surprised this simple solution wasn't offered here which will work in all cases.

var sending = 0;

$('#myForm').submit(function(){
if (sending == 0){

sending++;

// SUBMIT FORM

}else{
return false;
}
setTimeout(function(){sending = 0;},1000); //RESET SENDING TO 0 AFTER ONE SECOND
}

This only allows one submit in any one second interval.

Colin R. Turner
  • 1,323
  • 15
  • 24