JQuery onload and key up launch function

I have the following which I would like to run the first time the page loads. Then I would like it to run on the keyboard when the user makes a change. The function that I would like to run is very large (cut out for publication here), so I do not want to duplicate the function. Is there a way to call the onload function and then reuse it on the keyboard? Thanks 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
+5
source share
4 answers

try it

$(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​​​
+1
source

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

keyupfunction() called when the page loads for the first time and when the keyup event is triggered ... this is the 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
+5

.

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

If you want to use the function in several places, do not make it anonymous. Anonymous functions are a pain to reuse (you can still reuse them in certain cases via callee(deprecated), etc.)

Name the function instead. Store it in a readycleaning area:

 $(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
source

All Articles