Click here to Skip to main content
15,909,615 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Calling a js function on button click. The function gets called. I get the button object and call click() on it again(in the same function). I am not very clear of how the page life cycle goes but. the function isn't called again. What I think is - the flow should have gone recursive. Any guidance would help.
aspx markup:
ASP.NET
<asp:Button ID="btnTest" runat="server" Text="Click Me" OnClientClick="testJSfunc();"/> 

javascript
JavaScript
function testJSfunc() 
{ 
alert('TEST'); 
document.getElementById('<%=btnTest.ClientID %>').click(); 
}
Posted
Updated 12-Dec-11 7:59am
v2

1 solution

Try the following:

ASPX MARKUP
Make sure onclick="btnTest_Click" exists
C#
<asp:Button ID="btnTest" runat="server" Text="Click Me" OnClientClick="testJSfunc();" onclick="btnTest_Click"/> 


JavaScript
XML
<script type="text/javascript">
    function testJSfunc() {
        alert('TEST');
        __doPostBack('btnTest', 'OnClick');
    }
</script>


C#
CODE BEHIND

protected void btnTest_Click(object sender, EventArgs e)
   {
       /* your code */
   }


Let me know if you have any trouble.

[UPDATED]

If you want to execute the function twice only then apply the following code:

XML
<script type="text/javascript">
       var clickCount = 0;
       function testJSfunc() {
           if (clickCount < 1) {
               alert('TEST');
               //            __doPostBack('btnTest', 'OnClick');
               document.getElementById('<%=btnTest.ClientID %>').click();
           }
           clickCount = clickCount + 1;
       }
   </script>
 
Share this answer
 
v3
Comments
RaviRanjanKr 12-Dec-11 14:37pm    
Nice Answer, My 5!
Monjurul Habib 12-Dec-11 14:38pm    
thank you
Samresh.ss 12-Dec-11 14:52pm    
Thanks. But I wanted to call testJSfunc again inside the testJSfunc by getting the button object(btnTest) and calling click() on it. Or am I missing something.
Monjurul Habib 12-Dec-11 14:57pm    
if you do that it becomes recursive. What you want actually? what is the purpose for calling this function again? make it clear to help you.
Samresh.ss 12-Dec-11 18:09pm    
Yes sir. Thats my question. It should become recursive. But it doesn't. That is my query actually. Why doesn't it.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900