user1911703
user1911703

Reputation: 750

how to call a function from another function in Jquery

<script>
  $(document).ready(function(){
    //Load City by State
    $('#billing_state_id').live('change', function() {
       //do something
    });   
    $('#click_me').live('click', function() {
       //do something
       //need to recall $('#billing_state_id').live('change', function() { but how?
    });   
  });
</script>

Load City by State working fine but i don't know whether it's possible or not to call it within another function like $('#click_me').live('click', function().

Upvotes: 15

Views: 123207

Answers (3)

ganji
ganji

Reputation: 844

I think in this case you want something like this:

$(window).resize(resize=function resize(){ some code...}

Now u can call resize() within some other nested functions:

$(window).scroll(function(){ resize();}

Upvotes: 1

collapsar
collapsar

Reputation: 17238

wrap you shared code into another function:

<script>
  function myFun () {
      //do something
  }

  $(document).ready(function(){
    //Load City by State
    $(document).on('change', '#billing_state_id', function() {
       myFun ();
    });   
    $(document).on('click', '#click_me', function() {
       //do something
       myFun();
    });   
  });
</script>

Upvotes: 2

Jason P
Jason P

Reputation: 27012

I assume you don't want to rebind the event, but call the handler.

You can use trigger() to trigger events:

$('#billing_state_id').trigger('change');

If your handler doesn't rely on the event context and you don't want to trigger other handlers for the event, you could also name the function:

function someFunction() {
    //do stuff
}

$(document).ready(function(){
    //Load City by State
    $('#billing_state_id').live('change', someFunction);   
    $('#click_me').live('click', function() {
       //do something
       someFunction();
    });
  });

Also note that live() is deprecated, on() is the new hotness.

Upvotes: 19

Related Questions