Reputation: 1687
I have an ASP Server Button on a User Control that triggers a Server-Side OnClick event which works fine. But I need to trigger the OnClick event using JavaScript or JQuery.
I have tried the following methods but neither actually simulate the results as if a User were to actually click the button:
document.getElementById('<%=btnRefresh.ClientID%>').click();
$('#<%=btnRefresh.ClientID %>').click();
I suspected this was possibly because this emulates a OnClientClick event and not the Server; but I have found claims that this has worked for others in successfully triggering the Server Side OnClick event but this is not working for me.
Is there any other way to accomplish the task?
In response to the suggestion of AJAX. I have tried that approach but a PostBack is required for this task to successfully complete. The actual Click of the button produces the desired result, I can cause the event to trigger using AJAX but without the element of PostBack it fails.
Upvotes: 0
Views: 3924
Reputation: 75113
I have an ASP Server Button
so you have something like
<asp:Button ID="btnRefresh" Text="I'm a button" OnClick="btnRefresh_Click" />
In order to also execute a client call, prior to the server call, all you need is to attach a function or inline code to the OnClientClick
property:
<asp:Button ID="btnRefresh"
Text="I'm a button"
OnClick="btnRefresh_Click"
OnClientClick="btnRefreshClick" />
and in your javascript simple add that method
function btnRefreshClick() {
// your stuff goes here...
return true; // returning true (or nothing) will fire the server side click
// returning false will not fire it
}
Added: Misunderstood the question, so you want to fire a javascript event that will do the click
on the button automatically...
I just tested this code:
<body>
<form id="form1" runat="server">
<div>
<asp:Button ID="Button1" runat="server" Text="Button" OnClick="Button1_Click" /><br />
<asp:Label ID="Label1" runat="server" Text="Label"></asp:Label>
<br/>
<a href="#" class="a">fire button click event</a>
</div>
</form>
<script>
$(".a").click(function() {
//var elm = $("#" + "<%= Button1.ClientID %>"); elm.click(); // with jQuery
var elm = document.getElementById('<%=Button1.ClientID%>');
elm.click();
});
</script>
</body>
and I get the button to fire correctly, with or without jQuery:
screencast of this being executed: http://screencast.com/t/m4ohA9uW
Upvotes: 1