Friday, January 11, 2013

html form onsubmit event with two submit buttons

It is not possible to know which submit button is clicked in onsubmit() of form, when there are two submit buttons on the same form.


e.g.


<html>
<head>
<script>
function verifySubmit()
{
   alert("in verifySubmit");
   return false;
}
</script>
</head>

<body>

alohaaa
<form name="frm1" onsubmit="return verifySubmit();">
<input type="text" name="fname">
<input type="submit" value="Submit">
<input type="submit" value="Delete">

</form>

</body>
</html>



In above case, there is no way out to perform different operations depending on which submit is clicked; submit or delete.



SOLUTION ::





<script language="javascript" type="text/javascript">
    function verifyData(button) {
        // validate
       var returnVal;
        switch (button.value) {
            case "submit1":   
                alert("submit1");
                returnVal=true;
                break;
            case "submit2":
                alert("submit2");
                returnVal=false;
                break;
        };
        return returnVal;
    }

</script>

<form method="post">
    <input type="submit" value="submit1" onclick="return verifyData(this);">
    <input type="submit" value="submit2" onclick="return verifyData(this);">
</form>




NOTE:

  • Action is not present means, submit would reload this page
  • If onclick is true, it will submit the request.
  • If onlclick is false, it will not submit the request.







No comments:

Post a Comment