jQuery trigger change event doesn't work

16,270

Solution 1

You could avoid the usage of $().trigger by defining the functions to be used as event handlers in the global namespace (or in a wrapper function if you're worried about adding properties to the global object).

Add the event handler by naming the funciton you defined, and when you need to trigger the event handler you just invoke that function.

I'll give you an example:

function countryChange () {
  ...
}

$('#country').on('change', countryChange);

function init() {
  ...
  countryChange(); 
}

$(document).ready(function () {
  init();
}

Solution 2

You have to put your change events inside the callback function of $(document).ready(), anywhere before where you trigger them.

 $(document).ready(function(){

     $(selector).change(function(){
           ...
     });

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

 });

I strongly recommend to never bind your selectors outside the ready event.

Share:
16,270
stowka
Author by

stowka

Updated on June 04, 2022

Comments

  • stowka
    stowka almost 2 years

    I'm having an issue with my JavaScript code, I want to fire a change event when I load the page, it used to work in local but now it's online and nothing happens.

    Here's my code: (there's some php code, it works fine)

    $("#city").change(function() {
        console.log("city changed...");
        var city = $( "#city option:selected" ).val();
        $.get(
            "ajax.php",
            {
                page: "venues",
                city: city
            },
            function (data) {
                $("#venue").empty();
                $("#venue").append('<option selected disabled>--</option>');
                for(var i = 0; i < data.venues.length; i+=1) {
                    if (data.venues[i].id == <?php print $concert->getVenue()->getId(); ?>) {
                        $("#venue").append('<option value="'+data.venues[i].id+'" selected>'+data.venues[i].name+'</option>');
                    } else {
                        $("#venue").append('<option value="'+data.venues[i].id+'">'+data.venues[i].name+'</option>');
                    }
                }
                $("#label-venue").visible();
                $("#venue").visible();
    
                /*if (controlForm())
                    $("#submit").removeProp("disabled");
                else
                    $("#submit").addProp("disabled");*/
            }
        );
    });
    
    $("#country").change(function() {
        console.log("country changed...");
        var country = $( "#country option:selected" ).val();
        $("#country-city").html($( "#country option:selected" ).html());
        $.get(
            "ajax.php",
            {
                page: "cities",
                country: country
            },
            function (data) {
                $("#city").empty();
                $("#city").append('<option selected disabled>--</option>');
                $("#venue").empty();
                $("#venue").append('<option selected disabled>--</option>');
                for(var i = 0; i < data.cities.length; i+=1) {
                    if (data.cities[i].id == <?php print $concert->getVenue()->getCity()->getId(); ?>) {
                        $("#city").append('<option value="'+data.cities[i].id+'" selected>'+data.cities[i].name+'</option>');
                    } else {
                        $("#city").append('<option value="'+data.cities[i].id+'">'+data.cities[i].name+'</option>');
                    }
                }
                $("#label-city").visible();
                $("#city").visible();
                $("#city").trigger("change");
            }
        );
    });
    
    function init() {
        $.get(
            "ajax.php",
            {
                page: "countries"
            },
            function (data) {
                $("#country").empty();
                $("#country").append('<option selected disabled>--</option>');
                for(var i = 0; i < data.countries.length; i+=1) {
                    if (data.countries[i].id == <?php print $concert->getVenue()->getCity()->getCountry()->getId(); ?>) {
                        $("#country").append('<option value="'+data.countries[i].id+'" selected>'+data.countries[i].name+'</option>');
                    } else {
                        $("#country").append('<option value="'+data.countries[i].id+'">'+data.countries[i].name+'</option>');
                    }
                }
                $("#country").trigger("change");
            }
        );
    }
    
    $("#country-dismiss").click(function() {
        $("#country-name-en").val("");
        $("#country-name-nl").val("");
        $("#country-name-de").val("");
    });
    
    $("#city-dismiss").click(function() {
        $("#city-name-en").val("");
        $("#city-name-nl").val("");
        $("#city-name-de").val("");
    });
    
    $("#venue-dismiss").click(function() {
        $("#venue-name").val("");
        $("#venue-texte").val("");
        $("#venue-website").val("");
    });
    
    $("#country-submit").click(function() {
        console.log("adding country");
        var name_en = $("#country-name-en").val();
        var name_nl = $("#country-name-nl").val();
        var name_de = $("#country-name-de").val();
    
        $.post(
            "ajax.php?page=add_country",
            {
                en: name_en,
                nl: name_nl,
                de: name_de
            },
            function (data) {
                init();
                console.log(data);
            }
        );
    
    });
    
    $("#city-submit").click(function() {
        var name_en = $("#city-name-en").val();
        var name_nl = $("#city-name-nl").val();
        var name_de = $("#city-name-de").val();
        var country = $( "#country option:selected" ).val();
    
        $.post(
            "ajax.php?page=add_city",
            {
                country: country,
                en: name_en,
                nl: name_nl,
                de: name_de
            },
            function (data) {
                $("#country").trigger("change");
            }
        );
    });
    
    $("#venue-submit").click(function() {
        var name = $("#venue-name").val();
        var address = $("#venue-address").val();
        var website = $("#venue-website").val();
        var city = $( "#city option:selected" ).val();
    
        $.post(
            "ajax.php?page=add_venue",
            {
                city: city,
                name: name,
                address: address,
                website: website
            },
            function (data) {
                $("#city").trigger("change");
            }
        );
    });
    
    $( document ).ready(function() {
        (function($) {
            $.fn.invisible = function() {
                return this.each(function() {
                    $(this).css("visibility", "hidden");
                });
            };
            $.fn.visible = function() {
                return this.each(function() {
                    $(this).css("visibility", "visible");
                });
            };
        }(jQuery));
        init();
    });
    

    I hope someone will be able to see where I'm making a mistake (or several). Thanks!

  • showdev
    showdev about 10 years
    The OP already has an event listener for change. The question is why programmatically triggering the change fails.
  • stowka
    stowka about 10 years
    I have a console.log() already. I used the chrome console to fire the event manually after the page has loaded, nothing happens as if the function was empty. But when I really change the selected item, it works perfectly.
  • stowka
    stowka about 10 years
    Thank you, I'm gonna try this.
  • stowka
    stowka about 10 years
    It works! Thank you so much. I'm still wondering why the trigger didn't work though…
  • Rozen
    Rozen over 4 years
    mother ****, you saved my sanity dude!