select2简单例子
1.html中静态值
html
<%--multiple 为多选--%> <select multiple id="e1"> <option></option> <option value="AL">Alabama</option> <option value="WY">Wyoming</option> </select>
js
$(document).ready(function() { $("#e1").select2({ placeholder: "Choose a person", width:"200px", closeOnSelect: false }); });
2.通过js赋值:
html
<input type="hidden" id="e2" />
js
var data = [{id: 0, text:'story'},{id: 1, text:'bug'},{id: 2, text: 'task'}]; //或者一下形式都可,但必须是text属性 //var data = [{"id": "0", "text": "story"},{"id": "1", "text": "bug"},{"id": "2", "text": "task"}]; $("#e2").select2({ width:"200px", multiple:true, data:data });
js
//当数据源不是text属性时var source=[{id:0,tag:'enhancement'},{id:1,tag:'bug'},{id:2,tag:'duplicate'},{id:3,tag:'invalid'},{id:4,tag:'wontfix'}]; function format(item) { return item.tag; }
$("#e2").select2({ width:"200px", multiple:true, data:source, formatSelection: format, formatResult: format });
3.获取值
alert(JSON.stringify($('#e3').select2('data')))
请随手写下你的想法!!!