Problem with duplicate form sending

Asked

Viewed 551 times

1

Guys I’m having a problem sending duplicate form.

It occurs as follows. I have an html form, when the user of 2 quick clicks or quick click on enter he sends the form 2 times.

I tried to solve the problem as follows.

I made the form like this:

<form name='form'  onsubmit='envia_tranca();'>

And I put this javascript at the beginning of the page:

<script>
        function envia_tranca() {
            document.forms['form'].submit();
            document.forms['form'].elements['envia'].disabled = true;
        }
</script>

Well that works on Chrome and safari, but in IE the bug continues, someone can help me to solve the problem?

2 answers

3


Method 1: "unobtrusive"

Use unobtrusive code to disable sending the form after it has already been sent. Here is an example using jQuery.

$("form").submit(function() {
    $(this).submit(function() {
        return false;
    });
    return true;
});

Method 2: validation obsubmit()

There are also other ways to perform this validation, for example:

<form onsubmit="return validacao()">
  Input teste: <input type="text">
  <input type="submit" value="submit" />
</form>

<script type="text/javascript">
  var foiEnviado = false;    
    function validacao(){
      if(!foiEnviado) {
        foiEnviado = true;
        return ;
      }
      return false;
    }    
</script>

Method 3: jQuery plugin

Using a plugin called Safeform, the secret is to use the method data() to validate whether the form was sent or not. Thus, it is not necessary to validate buttons, in which the Internet Explorer very bad boss.

jQuery.fn.preventDoubleSubmission = function() {
  $(this).on('submit',function(e){
    var $form = $(this);

    if ($form.data('submitted') === true) {
      e.preventDefault();
    } else {
      $form.data('submitted', true);
    }
  });
  return this;
};

Use more or less like this:

$('form').preventDoubleSubmission();

Read more about the jQuery Safeform

  • I was able to make Method 2 work, but I wanted to know how to call Method 1 in the form

0

I’ve seen something similar using Jquery:

$("form").submit(function() {
    $(this).submit(function() {
        return false;
    });
    return true;
});

There is also a plugin called jquery-safeform that solves exactly this problem.

  • and how I call it in a form?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.