Javascript – How to run a javascript function before postback of asp.net button

asp.netjavascript

I'm using Javascript to create a DIV element and open up a new page by using onclientclick. This works great. Now, I need to write to it from the server side and this element must be created before it is posted back.

How do I get the javascript to execute before the postback?

Currently, I have to press the button twice because the element doesn't exist to write too on the first click.

To be clear, I need this to execute before the "OnClick" of the button.

Update: It looks like the Javascript function is called before the postback but the element is not updated until I run the second postback. Hmm

Update: Unfortunately it is a bit more complicated then this.

I'm creating a div tag in javascript to open a new window. Inside the div tag, I'm using a databinding syntax <%=Preview%> so that I can get access to this element on the server side. From the server side, I'm injecting the code.

I'm thinking this may be a chicken-egg problem but not sure.

UPDATE!

It is not the Javascript not running first. It is the databinding mechanism which is reading the blank variable before I'm able to set it.

Hmm

Best Answer

you don't have to rely on server controls to perform postbacks in asp.net. you can gain finer control of your app by posting from javascript whenever you are ready..

the framework auto generates a function called __doPostback(.....) and eventually calls it every time it needs to do a postback.

so. instead of using server control button, you can have a regular <button onclick="foo()" /> than once you're done performing all that you need, just call the __doPostback function.

asp.net gives you a nifty way to access that function with Page.GetPostbackClientEvent (i believe, but there are couple methods that support this methodology) http://msdn.microsoft.com/en-us/library/system.web.ui.page.getpostbackclientevent.aspx