12

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

Majid
  • 13,853
  • 15
  • 77
  • 113
Emech
  • 611
  • 1
  • 4
  • 16

5 Answers5

17

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);
lmcanavals
  • 2,339
  • 1
  • 24
  • 35
Emech
  • 611
  • 1
  • 4
  • 16
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" ... />
graphicdivine
  • 10,937
  • 7
  • 33
  • 59
  • 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 – Emech Mar 11 '12 at 12:19
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.

lmcanavals
  • 2,339
  • 1
  • 24
  • 35
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;
    }
});
davidthegrey
  • 1,205
  • 2
  • 14
  • 23
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>
Torrent Lee
  • 845
  • 6
  • 9