Safe submit with jQuery

This is just a simple way to prevent multiple form submissions.



View it in action in the video below.

Watch in full screen for best results.


 
Demo
Demo
Okay, lets get started.
What this will do is disable all form inputs when form submit button is clicked to prevent multiple form submission.
Then We will enable all the form inputs after a successful form submission.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
$(document).ready(function(){
    $("#submit").click(function(){
    /*Disable form inputs*/
    $(":input").attr("disabled", true);
    var dataString =  'name=test';
    $.ajax({
    type: "POST",
    url: "1.php",
    data: dataString,
    success: function(){
    /*Enable form inputs after form successfully submitted*/
    $(":input").removeAttr('disabled');
    }
    });
    return false;
    });
});

Now for the HTML
Below is just a form setup with an input field and submit button.

1
2
3
4
5
6
7
<form>
     Name:<input type="test" name="name" id="name" />
     <input type="submit" name="submit" id="submit" />
</form>

Now lets put it all together.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
<!-- Created by Barrett at RRpowered -->
<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="UTF-8" />
        <title>Safe submit with jQuery</title>
        <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/
jquery/1.7.1/jquery.min.js"></script>
        <script type="text/javascript">
            $(document).ready(function(){
               $("#submit").click(function(){
               /*Disable form inputs*/
               $(":input").attr("disabled", true);
               var dataString =  'name=test';
               $.ajax({
               type: "POST",
               url: "1.php",
               data: dataString,
               success: function(){
               /*Enable form inputs after form successfully submitted*/
               $(":input").removeAttr('disabled');
               }
               });
               return false;
               });
            });
        </script>
    </head>
    <body>
        <form>
            Name:<input type="test" name="name" id="name" />
            <input type="submit" name="submit" id="submit" />
        </form>
    </body>
</html>

ADVERTISEMENT

Tags: , , , ,

Enjoyed this Post?

Subscribe to our RSS Feed, Follow us on Twitter or simply recommend us to friends!

Discussion