1

At the moment I have a function that is changed when you select something in a dropdown box. it all works fine. But I want to also call the same .change function in a different function. Is this even possible and if so, how do I do it? Here is the function I wanna call:

 $(document).ready(function(){
     $('.action').change(function(){
      .....
      .....

I hope I provided you with enough information to answer my question, thanks in advance.

1
  • 1
    You can create a function, something like function actionChange() { ..... <logic here> .... } and assign that function the the change event $('.action').change(actionChange); and then you can either call the function directly (actionChange()) and it will also be called on the change event Commented Feb 20, 2020 at 15:44

2 Answers 2

2

You can use .on() and than .trigger()

jQuery(function($){  // DOM ready and $ alias in scope.

    $('.action').on('change', function(){
      console.log("Foobarbaz");
    });
    
    $('.action').trigger('change');
   
    $('#myAction_3').trigger('change'); // or a specific one
    
});

If you want to trigger only a specific "change" you can namespace your event name:

$('.action').on('change.foo', function(){
  console.log("Foobarbaz");
});

$('.action').trigger('change.foo');
       

Sign up to request clarification or add additional context in comments.

Comments

1

If I understood you correctly, you want the same thing to happen at two different places. If that is the case, then you could do something like this:

$(document).ready(function(){
   $('.action').change(function(){
       onSelectChange(); // call the function on select change
   });

   function onSelectChange()
   {
        // write your code here
   } 

   // your other function which needs to do the same thing as .action change function
   function myOtherFunction()
   {
      onSelectChange(); // call the same function here as well
   }
});

1 Comment

The accepted answer, to me, looks to encourage the interweaving of application logic and jQuery in a most pernicious way. This the sane solution.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.