November 8, 2012

Using onChange on Select Option

Question by deetu

I have a select option box that is dynamically populated, so if i change the select some other boxes are filled, and i can delete them too.
Which also deletes the option from the select box, this works fine, but when i delete the options and i have just one left in the box, there seem to be no way to fire the option.

$("#email_name").on("change", function(){
    var componentkeys = myDailyemail.getKeys($("#Component").val());
    $.each(componentkeys, function(kIndex, kItem) {
        $("#key").append($("<option/>").val(kItem).text(kItem.toUpperCase()));
    });
});

Answer by iMoses

You can automatically trigger a change event after you populated the select element, making it as if the user already selected the first option.

$("#email_name").on("change", function(){
    var componentkeys = myDailyemail.getKeys($("#Component").val());
    $.each(componentkeys, function(kIndex, kItem) {
        $("#key").append($("<option/>").val(kItem).text(kItem.toUpperCase()));
    });
    $("#key").trigger("change"); // trigger key
}).trigger("change"); // trigger email_name

I wasn’t sure what you wanted to trigger so I entered both possibilities.

Answer by Starx

You can use .trigger() to fire events manually.

Insert following, where needed.

$("#email_name").trigger('change');

Author: Nabin Nepal (Starx)

Hello, I am Nabin Nepal and you can call me Starx. This is my blog where write about my life and my involvements. I am a Software Developer, A Cyclist and a Realist. I hope you will find my blog interesting. Follow me on Google+

...

Please fill the form - I will response as fast as I can!