js拼接普通SELECT变为select2样式下拉框

html:

<table id="ruleTable" class="table" style="width:274px">
                    <thead>
                        <tr>
                            <th style="width:150px;">筛选类别</th>
                            <th style="width:250px;">筛选值</th>
                            <th style="width:44px;">操作</th>
                            <th><input type="button" class="btn btn-primary" onclick="addRow()" value="增加"/></th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr>
                            ${search_type}
                        </tr>
                    </tbody>
                </table>

js:

function addRow(){

$.ajax({
                    url : '${ctx}/panelinfo/panelInfo/initSearch',
                    type : "post",
                    data : {
                        type : type
                    },
                    cache : false,
                    async:false,
                    error : function() {
                    },
                    success : function(data) {
                       // var va="";
                        var list = data.list;
                        if (list && list.length != 0) {
                            optionstr = "<select class=\"input-medium\" style=\"width:120px;\" name=\"typeselect\" id=\"typeselect" onchange=\"typeSelectChange(this.id,this.value)\">";
                            $.each(list, function(index, item) {
                                optionstr+="<option value=\""+item.value;
                                optionstr+="\"";
                                if(index==0){
                                    dt=item.value;
                                    optionstr += " selected=\"selected\" "; //默认选中
                                   // va=item.name;
                                }
                                optionstr+=" >"+item.label+ "</option>";
                             });
                            optionstr += "</select>";
                            $("#ruleTable tbody").append(optionstr);

//使用样式前

                             $("#typeselect").select2();//初始化为select2标签样式

//使用样式后
                        }else{
                            if(!isNull(optionstr)){
                                jBox.tip("类别数据字典未填写!", 'info');
                                return;                
                            }
                        }
            
                    }

                });

拓展:

$("#typeselect").empty();   //将select置空

$("#s2id_typeselect  span.select2-chosen").eq(0).text("值");//给select2下拉框初始化赋值

}
 

猜你喜欢

转载自blog.csdn.net/world_the_begin/article/details/88680435
今日推荐