Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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
like image 939
Bocker Avatar asked Jun 01 '12 08:06

Bocker


3 Answers

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
like image 96
Pranay Rana Avatar answered Nov 01 '22 00:11

Pranay Rana


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​​​
like image 3
rt2800 Avatar answered Nov 01 '22 00:11

rt2800


You could trigger the event once on load.

$("td, input").keyup(
  function (){
    var col_1revenue = $(".Col1Receipts, .Col1Receipts input").sum(); 
  } 
).keyup();
like image 2
xdazz Avatar answered Oct 31 '22 23:10

xdazz