Bocker
Bocker

Reputation: 91

jQuery run function onload and key up

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

Upvotes: 5

Views: 6131

Answers (4)

Pranay Rana
Pranay Rana

Reputation: 176896

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

Upvotes: 6

Manishearth
Manishearth

Reputation: 16188

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

Upvotes: 0

rt2800
rt2800

Reputation: 3045

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​​​

Upvotes: 3

xdazz
xdazz

Reputation: 160833

You could trigger the event once on load.

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

Upvotes: 2

Related Questions