Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to call a asp:Button OnClick event using JavaScript? [duplicate]

I have a question, I have a button like below:

<asp:Button ID="savebtn" runat="server" OnClick="savebtn_Click" Visible="false" />

I then have HTML button like like below:

<button id="btnsave" onclick="fncsave">Save</button>

I have the javascript below:

<script type="text/javascript">
     function fncsave()
     {
        document.getElementById('<%= savebtn.OnClick %>').click()
     }
</script>

My question now is, how can I call the asp:Button OnClick from the HTML button? I have read you can do this by calling from JavaScript by Id but is not working.

Any help will be really appreciate it.

Thank you

like image 704
jorame Avatar asked Mar 05 '13 04:03

jorame


2 Answers

Set style= "display:none;". By setting visible=false, it will not render button in the browser. Thus,client side script wont execute.

<asp:Button ID="savebtn" runat="server" OnClick="savebtn_Click" style="display:none" />

html markup should be

<button id="btnsave" onclick="fncsave()">Save</button>

Change javascript to

<script type="text/javascript">
     function fncsave()
     {
        document.getElementById('<%= savebtn.ClientID %>').click();
     }
</script>
like image 119
Sunny Avatar answered Oct 22 '22 14:10

Sunny


If you're open to using jQuery:

<script type="text/javascript">
 function fncsave()
 {
    $('#<%= savebtn.ClientID %>').click();
 }
</script>

Also, if you are using .NET 4 or better you can make the ClientIDMode == static and simplify the code:

<script type="text/javascript">
 function fncsave()
 {
    $("#savebtn").click();
 }
</script>

Reference: MSDN Article for Control.ClientIDMode

like image 21
Glenn Ferrie Avatar answered Oct 22 '22 15:10

Glenn Ferrie