简体   繁体   中英

How to find source of submit using javascript

Please help me to solve this problem: I have a form in which i have written onSubmit calling a javascript function. please tell me in that javascript function how can i check that who was the event generater ( i mean on which button click this even raised).. Note: onsubmit function call is in form tag.. i am using javascript and asp.net My code is like this:

 <form id="form1" runat="server" onsubmit="return CheckForm()">

    <script type="text/javascript" language="javascript">
        function CheckForm()
            {
            some code here
            } 
    </script>

i dont want to change any functionality.. i have got a dropdownlist which is causing postback.. i want that when this dropdownlist raise post back either i should know that its raised by dropdownlist or that function should not be called by dropdownlist's postback

you can pass this like here is an example...

this.TextBox1.Attributes.Add("onkeypress", "button_click(this,'" + this.Button1.ClientID + "')");

function button_click(objTextBox,objBtnID)
{
    if(window.event.keyCode==13)
    {
        document.getElementById(objBtnID).focus();
        document.getElementById(objBtnID).click();
    }
}

You could add an onclick event to the submit buttons that will set a variable. This value can then be used in the onsubmit event to figure out which button was clicked:

The form:

<form action="" method="get" id="frmOne" onsubmit="return checkVal()">
    <input type="submit" id="btnOne" value="hello01" onclick="testtwo(1)" />
    <input type="submit" id="btnTwo" value="hello02" onclick="testtwo(2)" />
</form>

The script:

<script type="text/javascript">
    var iVal = 0;
    function checkVal() {
        if (iVal == 1) {
            // ... 
            return false;
        } else {
            if (iVal == 2) {
                // ...
                return true;
            }
        }
    }
    function testtwo(val) {
        iVal = val;
    }
</script>
<script type="text/javascript">
   var button=''

   // call this function on button click
   function  clickButtonName(name){
          button=name
   }

   // onSubmit function check for 'button' Variable to find out which event is clicked
don't forget to reset button variable.

</script>

But remember your form is also get sumitted when you are in a textfield inside the form and click on "Enter" button.I think then You have to disable form submission using onkeypress and event class of javascript.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM