简体   繁体   中英

How can I trigger an on change function to also trigger on load?

In the example below, I would like it to trigger the $(".hidden").show("slide"); when the page loads. Essentially, I would like for function to trigger when that value is loaded onto the page. Also the id's q1, q2 and q3 are s.

$(function(){

    $('#questions').change(function(){
        var q1Val = $('#q1 :selected').val();
        var q2Val = $('#q2 :selected').val();
        var q3Val = $('#q3 :selected').val();

        if (q1Val == "Treatment Rendered" || q1Val == "Unknown") {
            $(".hidden").show("slide");
        }
        else {
            $(".hidden:visible").hide("slide");
        }
    });
});

Just trigger the event manually:

$('#questions').change(function(){
   // awesome code....
}).trigger('change');

http://api.jquery.com/trigger/

As well as Felix's trigger method you could move the inner on your change function to a separate function and then call it inside and outside your change function. For example:

function functionName(){
   var q1Val = $('#q1 :selected').val();
   var q2Val = $('#q2 :selected').val();
   var q3Val = $('#q3 :selected').val();

   if (q1Val == "Treatment Rendered" || q1Val == "Unknown") {
      $(".hidden").show("slide");
   }
   else {
      $(".hidden:visible").hide("slide");
   }
}

$(function(){
   $('#questions').change(functionName);
   functionName();
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM