holland
holland

Reputation: 2182

Fire jQuery .on('change') always at least once

I often find myself using pieces of code like the following:

$('[name=myradio]').on('change', function(){

    if($(this).val() == 0){
        $('#div').toggle();
    }

    else if(....){
        $('#div2').toggle();
    }

    //...and more code going on
});

However, often I want to execute these pieces of code always at least once (for example when validation fails)! Of course I could make a method of this code and then execute the method from within the change anonymous function, as wel as in a $(document).ready() method, but I wonder if there is an easy way to execute that code at least once but also keep that code only in the change method to keep everything nice and clean instead of making a method for something that would be used only twice.

Upvotes: 0

Views: 82

Answers (2)

coder123
coder123

Reputation: 33

Use trigger() method. This way you can keep the code only in the change method and trigger it from anywhere.

$(selector).trigger("change");

Upvotes: 0

Shiran Dror
Shiran Dror

Reputation: 1480

you can just trigger change in $(document).ready(...)

$(document).ready(function() {
  $('[name=myradio]').on('change', function() {

    if ($(this).val() == 0) {
      $('#div').toggle();
    } else if (....) {
      $('#div2').toggle();
    }

    //...and more code going on
  }).trigger("change");
});

Upvotes: 1

Related Questions