Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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().

like image 518
user1911703 Avatar asked Aug 29 '13 15:08

user1911703


People also ask

How can use one function in another function in JQuery?

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(); }); });

How do you call one function after another in JQuery?

You should use a callback parameter: function Typer(callback) { var srcText = 'EXAMPLE '; var i = 0; var result = srcText[i]; var interval = setInterval(function() { if(i == srcText. length - 1) { clearInterval(interval); callback(); return; } i++; result += srcText[i].

Can we write function inside function in JQuery?

Yes, you can.

How do I execute one function after another?

Simply put: A callback is a function that is to be executed after another function has finished executing — hence the name 'call back'. More complexly put: In JavaScript, functions are objects. Because of this, functions can take functions as arguments, and can be returned by other functions.


2 Answers

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.

like image 96
Jason P Avatar answered Sep 23 '22 03:09

Jason P


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>
like image 34
collapsar Avatar answered Sep 22 '22 03:09

collapsar