javascript html select add optgroup and option dynamically

前端 未结 3 1328
旧时难觅i
旧时难觅i 2021-01-05 02:13

let say i have a

提交评论

  • 2021-01-05 03:00

    This is for empty default select options and add new

    var select_option = '';
    for (i=0; i<response.length; i++){
    options += '<option value="'+i+'">'+i+'</option>'
    }    
    
    $('.selectclassname').html('').append(select_option)
    
    0 讨论(0)
  • 2021-01-05 03:10

    Well, how about jQuery ?

    http://jsfiddle.net/ZP4E9/2/

    var opt = {
        friendchat:[
            {name:"somefriend1"},
            {name:"somefriend2"}
        ],
        otherchat:[
            {name:"someother1"},
            {name:"someother2"}
        ],
        friendrequest:[
            {name:"somerequest1"},
            {name:"somerequest2"}
        ],
        sentrequest:[
            {name:"somesent1"},
            {name:"somesent2"}
        ]
    };
    
    $(function(){
        var $select = $('#mySelect');
        $.each(opt, function(key, value){
            var group = $('<optgroup label="' + key + '" />');
            $.each(value, function(){
                $('<option />').html(this.name).appendTo(group);
            });
            group.appendTo($select);
        });
    });
    
    0 讨论(0)
  • 提交回复
    热议问题