jQuery— Populate select from json

前端 未结 8 1556
花落未央
花落未央 2020-12-08 01:56

I have a map in my java sevlet and converting it to a json format that works right.

When I do this function below it creates a drop down, but it puts every character

相关标签:
8条回答
  • 2020-12-08 02:40

    fiddle

    var $select = $('#down'); 
    $select.find('option').remove();  
    $.each(temp,function(key, value) 
    {
        $select.append('<option value=' + key + '>' + value + '</option>');
    });
    
    0 讨论(0)
  • 2020-12-08 02:42

    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('<option value="'+key+'"+>'+datas[key]+'</option>');
                    }
                }
                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

    0 讨论(0)
提交回复
热议问题