[ACCEPTED]-How to run a javascript function before postback of asp.net button-asp.net
Hook up OnClientClick to some javascript function that 2 returns true or false. The postback occurs 1 if it returns true else it is canceled.
<asp:Button id="MyButton" runat="Server" Text="Close"
OnClientClick="return PromptClose();"/>
<script type="text/javascript">
function PromptClose(){
return prompt("Do you really want to close this window?");
}
</script>
You could use the onsubmit
event of your page's 16 form. This happens before the form is submitted, and 15 will allow you to stop submission of the 14 form if you need by cancel bubbling. In 13 case you need this, the last 2 lines in 12 this example will cancel bubbling across 11 browsers.
<form runat="server" onsubmit="ShowLoading()">
</form>
<script type="text/javascript">
function ShowLoading(e) {
var div = document.createElement('div');
var img = document.createElement('img');
img.src = 'http://www.oppenheim.com.au/wp-content/uploads/2007/08/ajax-loader-1.gif';
div.innerHTML = "Loading...<br />";
div.style.cssText = 'position: fixed; top: 30%; left: 40%; z-index: 5000; width: 222px; text-align: center; background: #fff; border: 1px solid #000';
div.appendChild(img);
document.body.appendChild(div);
// These 2 lines cancel form submission, so only use if needed.
window.event.cancelBubble = true;
e.stopPropagation();
}
</script>
The JavaScript above is just for 10 example, however this is (in my opinion) the 9 preferred way to do what you're looking 8 for. It looks something like this (in the 7 center of the screen):
This will 6 work for any element that raises a PostBack, so 5 you don't have to manually call ShowLoading()
on every 4 button or form element you may have on your 3 page. I would replace the contents of ShowLoading()
with 2 some real loading functionality and not 1 just the example code I threw together.
Look at OnClientClick, you can add a call 4 to a js function, or inline JS there.
Or 3 you can wire into the button with JQuery 2 and display a modal dialog with an async 1 callback.
More Related questions
We use cookies to improve the performance of the site. By staying on our site, you agree to the terms of use of cookies.