5

I have the following, which I would like to run for the first time when the page loads. Then I would like it to run on keyup as user makes changes. The function I would like to run is very large (stripped down for posting on here) so I don't want to duplicate the function. Is there a way to call the function onload and then reuse it on keyup? Thank you

  $(document).ready(function() {
     // this calculates the sum for some text nodes
     $("td, input").keyup(
        function (){
          var col_1revenue = $(".Col1Receipts, .Col1Receipts input").sum(); 
        } // function
      ); // keyup
    }); // document ready
1
  • dont forget to mark it as accepted if you got the info you want.. Jun 1, 2012 at 10:06

4 Answers 4

6

An easy way is to create a function and then call it from both:

keyupfunction() is called the first time the page load completes and when the keyup event gets fired... that is the whole purpose of using a function in a programming language.

$(document).ready(function() {
         keyupfunction(); //first call
         // this calculates the sum for some text nodes
         $("td, input").keyup(keyupfunction); // keyup
        }); // document ready

common function

function keyupfunction(){
              var col_1revenue = $(".Col1Receipts, .Col1Receipts input").sum(); 
} // function
3

Try this

$(document).ready(function() {
    XX();
    // this calculates the sum for some text nodes
    $("td, input").keyup(XX); // keyup


    function XX() {
        var col_1revenue = $(".Col1Receipts, .Col1Receiptsinput").sum();
    } // function    
}); // document ready​​​
0
2

You could trigger the event once on load.

$("td, input").keyup(
  function (){
    var col_1revenue = $(".Col1Receipts, .Col1Receipts input").sum(); 
  } 
).keyup();
0

If you want to use a function in multiple places, don't make it anonymous. Anonymous functions are a pain to reuse (you still can reuse them in certain cases via callee (deprecated), etc.)

Name the function, instead. Keep it inside the scope of ready to be clean:

 $(document).ready(function() {
     // this calculates the sum for some text nodes
     function myfunc(){
          var col_1revenue = $(".Col1Receipts, .Col1Receipts input").sum(); 
           //etc
             //etc
        } // function
     $("td, input").keyup(myfunc); // keyup
     myfunc()//call function;
    }); // document ready
0

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.