On Item Added event on an Drop Down List (Option selector)

Given a drop down list, is there any way to subscribe a javascript even which will be fired when a new item is added to the list?

I’d like something like the following to work

Asked on April 7, 2016 in HTML,   Javascript,   jQuery.
Add Comment
1 Answer(s)

This should work for all browsers (including explorer, which is a bugger about this sort of thing).

var option = document.createElement("option");
option.text = 'The visual value';
option.value = 'Th submitted value';
$("select")[0].options.add(option);

EDIT:
I should probably stop being slack and give you the full code to make this work as a jQuery plugin.

(function($) {
    $.fn.add_option = function(options) {
        var config = {
            value:0,
            text:0
        }
        config = $.extend(config, options);
        return this.each(function() {
            var option = document.createElement("option");
            option.text = config.text;
            option.value = config.value;
            $(this)[0].options.add(option);
            alert(config.text+ " has just been added to the list of options");
        }
    }
})(jQuery);
$(document).ready(function() {
    $('#id_of_select_dropdown').add_option({text:'My new text value', value:'new'});
});
Answered on April 7, 2016.
Add Comment

Your Answer

By posting your answer, you agree to the privacy policy and terms of service.