Thursday, 11 July 2013

Use jquery to prevent double submit


Recently, I was engaged in a web development project. We have encounted the very famous old problem of double submit in web application. Actually, we have many ways to solve it. We can prevent the double submit on server side. However, we do it in client side this time.

Here, I summarized two method of of preventing double submit in client side javascript.

(1) For html button, we can use jquery to disabled the button. Example code is shown here:

<input type="button" value="Click"id="subBtn"/>  
<script type="text/javascript">  

$("#subBtn").click(function(){  
   // Disabled the button
   $(this).attr("disabled","disabled");  
   
   //execute your function e.g. submit a form
   myFunc();  
});

function myFunc(){  
    // ...
    // code
    // ...
    // execute your logic here
    // remove the diabled  attribute and re-enabled the button again
    $("#subBtn").removeAttr("disabled");  
}  
  
</script> 


(2) For html anchor, we can use redirect the event handler of the anchor to another function after the first click.

<a href="javascript:;" onclick="return funcOne();">Click</a>  
<scripttypescripttype="text/javascript">  
function funcOne(){  
    alert("Clickthe button!");  

   //After the first click, funcTwo will be assined to funcOne.
    funcOne=funcTwo;  
    return false;  
}  
function funcTwo(){  
 //function two will not do anything
    return false;  
}  
</script>


0 comments:

Post a Comment