jQuery— Populate select from json

前端 未结 8 1555
花落未央
花落未央 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:15
    $(JSON.parse(response)).map(function () {
        return $('<option>').val(this.value).text(this.label);
    }).appendTo('#selectorId');
    
    0 讨论(0)
  • 2020-12-08 02:16

    I believe this can help you:

    $(document).ready(function(){
        var temp = {someKey:"temp value", otherKey:"other value", fooKey:"some value"};
        for (var key in temp) {
            alert('<option value=' + key + '>' + temp[key] + '</option>');
        }
    });
    
    0 讨论(0)
  • 2020-12-08 02:21

    I just used the javascript console in Chrome to do this. I replaced some of your stuff with placeholders.

    var temp= ['one', 'two', 'three']; //'${temp}';
    //alert(options);
    var $select = $('<select>'); //$('#down');                        
    $select.find('option').remove();                          
    $.each(temp, function(key, value) {              
        $('<option>').val(key).text(value).appendTo($select);
    });
    console.log($select.html());
    

    Output:

    <option value="0">one</option><option value="1">two</option><option value="2">three</option>

    However it looks like your json is probably actually a string because the following will end up doing what you describe. So make your JSON actual JSON not a string.

    var temp= "['one', 'two', 'three']"; //'${temp}';
    //alert(options);
    var $select = $('<select>'); //$('#down');                        
    $select.find('option').remove();                          
    $.each(temp, function(key, value) {              
        $('<option>').val(key).text(value).appendTo($select);
    });
    console.log($select.html());
    
    0 讨论(0)
  • 2020-12-08 02:22

    Only change the DOM once...

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

    That work fine in Ajax call back to update select from JSON object

    function UpdateList() {
        var lsUrl = '@Url.Action("Action", "Controller")';
    
        $.get(lsUrl, function (opdata) {
    
            $.each(opdata, function (key, value) {
                $('#myselect').append('<option value=' + key + '>' + value + '</option>');
            });
        });
    }
    
    0 讨论(0)
  • 2020-12-08 02:34

    I would do something like this:

    $.each(temp,function(key, value) 
    {
        $select.append('<option value=' + key + '>' + value + '</option>');
    });
    

    JSON structure would be appreciated. At first you can experiment with find('element') - it depends on JSON.

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