I wanna do something in javascript before page goes for post back.
How to run a javascript function before any asp.net postback?
$('form').submit(function () {
alert('hello');
});
It doesn't work... :(
I wanna do something in javascript before page goes for post back.
How to run a javascript function before any asp.net postback?
$('form').submit(function () {
alert('hello');
});
It doesn't work... :(
I find the way, in the asp.net forums and it was a some code in codebehind.
Just add this to your Page_Load event handler, changing the javaScript string to what you want to happen.
string scriptKey = "OnSubmitScript";
string javaScript = "alert('RegisterOnSubmitStatement fired');";
this.ClientScript.RegisterOnSubmitStatement(this.GetType(), scriptKey, javaScript);
If you want to do something client-side before asp's postback, try using the OnClientClick
attribute of the asp:button
, eg:
<asp:Button OnClick="submit" OnClientClick="myPrePostbackFunction()" Text="Submit" runat="server" ... />
try:
$('form').submit(function () {
return confirm('you sure?');
});
The form won't be submitted unless you return true
and before that you can do all you want.
It doesn't have to be a confirm()
call of course.
In year 2021, I'm completey getting rid of jQuery. To do this, I add to my page javascript:
document.forms[0].addEventListener('submit', e => {
if (conditionPreventingPostBack) {
e.preventDefault();
return false;
}
});
try this?
<form name="someform">
<input type="submit" value="" />
</form>
<script type="text/javascript">
document.someform.onsubmit = function ( e ) {
e = e|| window.event;
if ( !confirm ( "sure?") ){
e.returnValue ? ( e.returnValue = false ): e.preventDefault();
}
}
// then jquery version
$("form").bind("submit", function ( e ) {
if ( !confirm ( "sure?" ) ){
e.preventDefault();
}
})
</script>