Populate dropdown select with array using jQuery

后端 未结 8 1906
花落未央
花落未央 2020-11-29 08:07

I am trying to populate a dropdown select with an array using jQuery.

Here is my code:

        // Add the list of numbers to the drop down here
              


        
8条回答
  •  南笙
    南笙 (楼主)
    2020-11-29 08:23

    A solution is to create your own jquery plugin that take the json map and populate the select with it.

    (function($) {     
         $.fn.fillValues = function(options) {
             var settings = $.extend({
                 datas : null, 
                 complete : null,
             }, options);
    
             this.each( function(){
                var datas = settings.datas;
                if(datas !=null) {
                    $(this).empty();
                    for(var key in datas){
                        $(this).append('');
                    }
                }
                if($.isFunction(settings.complete)){
                    settings.complete.call(this);
                }
            });
    
        }
    
    }(jQuery));
    

    You can call it by doing this :

    $("#select").fillValues({datas:your_map,});
    

    The advantages is that anywhere you will face the same problem you just call

     $("....").fillValues({datas:your_map,});
    

    Et voila !

    You can add functions in your plugin as you like

提交回复
热议问题