Vince Vince - 7 months ago 9
Javascript Question

How to call one function from within another function within an event in Javascript

I want to be able to put the code in one place and call it from several different events.

Currently I have a selector and an event:

//snippet

$("input[type='checkbox']").on('click',function() {

// code works here//

}


I use the same code elsewhere in the file, however using a different selector.

//snippet
$(".product_table").on('change', '.edit_quantity', function (){

//code works here//

}


I have tried following the advice given elsewhere on StackOverflow, to simply give my function a name and then call the named function but that is not working for me. The code simply does not run.

//snippet
$(".product_table").on('change', '.edit_quantity', function (){

calculateTotals(){
//code does not work//
}
}


So, I tried putting the code into it's own function separate from the event and call it inside the event, and that is not working for me as well.

calculateTotals(){

//code does not work//

}


So what am I doing wrong ?

Answer

You could pass your function as a variable.

You want to add listeners for events after the DOM has loaded also, JQuery helps with $(document).ready(fn);

To fix your code:

 $(document).ready(function() {
   $("input[type='checkbox']").on('click', calculateTotalsEvent)
   $(".product_table").on('change', '.edit_quantity', calculateTotalsEvent)
 });

 function calculateTotalsEvent(evt) {
   //do something 
   alert('fired');
 }