13

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... :(

5 Answers 5

18

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);
Sign up to request clarification or add additional context in comments.

1 Comment

+1 I know how old this is, but thank you so much! It helped me a lot.
5

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" ... />

1 Comment

i know that, but i have lots of asp element on page , i want to do this code before any postback, not for a special button or element
2

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.

1 Comment

Quite odd, what browser are you using to test?
1

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;
    }
});

Comments

0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.