0

I have the following line being ran from Visual Basic:

ScriptManager.RegisterStartupScript(Page, Page.GetType, "populatePayPlan", "populatePayPlan();", True)

and it will run that javascript on every postback. I simply only want to run it on a checkbox.CheckChanged just once then never again no matter what. This has to be possible, I'm just missing something?

This was helpful: Execute javascript function after asp.net postback without Ajax

But not exactly what I needed.

1
  • Use a Session or ViewState key to store whether or not you've registered that script already, and if you have, don't register it? Commented Sep 26, 2012 at 19:30

1 Answer 1

1

One trick to make this happen would be to use a closure to ensure the function is only executed once:

var myFunction = (function () {
    var neverCalled = true;
    return function (arg, arg2, arg3) { //Any args for myFunction should be set here
        if(neverCalled) {
            neverCalled = false;
            //Put your function code here.

            return true; //or whatever
        } 
        return false; //or do nothing, or whatever
    };
}());

So when the function is "declared", it immediately evaluates the outer function and sets neverCalled to true, it then returns the inner function (this would be the function you want to execute only once) into the myFunction variable (or in your case, you want it to be the populatePayPlan variable I think).

The first time you call myFunction, it will run, but set neverCalled to false. Any subsequent executions of the function will skip the block and do nothing. It's a simple and nifty trick that takes advantage of JavaScript's first-class functions and closures aspects and should take care of your needs.

UPDATE:

Here's how it should run (note I modified the example code above):

myFunction(); //is true;
myFunction(); //is false;
myFunction(); //is false;

Just make sure to declare it somewhere where you can access it and don't call it until you need it. Hope that helps!

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks for your reply. For whatever reason I just couldn't get that piece of code to work. It just never executes the code inside the deep nested function. Thanks though!

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.