天天看點

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" οnclick="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" οnchange=\"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);

//使用樣式前

js拼接普通SELECT變為select2樣式下拉框

                             $("#typeselect").select2();//初始化為select2标簽樣式

//使用樣式後

js拼接普通SELECT變為select2樣式下拉框

                        }else{

                            if(!isNull(optionstr)){

                                jBox.tip("類别資料字典未填寫!", 'info');

                                return;                

                            }

                        }

                    }

                });

拓展:

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

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

}