0

I've found many threads on combining click and change jquery events. But I'm not sure how to combine a basic click event with this specific event for Bootstrap Switch. The following two events should have the same code. What is the best way to combine them, so I don't have repeat the same code twice?

1.

$('#regular-product .cancel').click(function(e){

   // SAME CODE GOES HERE //

});

2.

$('#regular-product .toggle').on('switchChange.bootstrapSwitch', function(event, state) {

    if ($('#regular-product .bootstrap-switch').hasClass('bootstrap-switch-off')) {

      // SAME CODE GOES HERE //

    }       
});

Here is an answer I found that I wasn't able to repeat for this. (Jquery combine click and change for one execution) Perhaps it's not the right method in this case?

Community
  • 1
  • 1
Lindsay
  • 127
  • 1
  • 3
  • 11

2 Answers2

0

Wrap your code into a function.

E.g.:

var myHandler = function()  {
  // do here some stuff you want to
};
$('#regular-product .cancel').click(myHandler);
$('#regular-product .toggle').on('switchChange.bootstrapSwitch', myHandler);
DCrystal
  • 711
  • 5
  • 11
0

I am not sure if I understand correctly but I suggest to just define a javascript function which evaluates your code and call that function in both cases.

stefanr
  • 76
  • 4