为什么80%的码农都做不了架构师?>>>
最终效果
首先我们要有一个基础的文本框
<input name="test" type="hidden" id="userSelect" style="width: 600px" value="上海^漳州" />
使用本地数据的写法
$('#userSelect').select2({placeholder: "请输入",minimumInputLength : 1,multiple : true,separator : "^", // 分隔符maximumSelectionSize : 5, // 限制数量initSelection : function (element, callback) { // 初始化时设置默认值var data = [];$(element.val().split("^")).each(function () {data.push({ id: this, text: this });});callback(data);},createSearchChoice : function(term, data) { // 创建搜索结果(使用户可以输入匹配值以外的其它值)return { id: term, text: term };},formatSelection : function (item) { return item.id; }, // 选择结果中的显示formatResult : function (item) { return item.id; }, // 搜索列表中的显示data: {results: [{ id: "北京", text: "bj beijin 北京" },{ id: "厦门", text: "xm xiamen 厦门" },{ id: "福州", text: "fz fuzhou 福州" }]}});
使用异步数据的写法
脚本
$('#userSelect').select2({placeholder: "请输入",minimumInputLength : 1,multiple : true,separator : "^", // 分隔符maximumSelectionSize : 5, // 限制数量initSelection : function (element, callback) { // 初始化时设置默认值var data = [];$(element.val().split("^")).each(function () {data.push({id: this, text: this});});callback(data);},createSearchChoice : function(term, data) { // 创建搜索结果(使用户可以输入匹配值以外的其它值)return { id: term, text: term };},formatSelection : function (item) { return item.id; }, // 选择结果中的显示formatResult : function (item) { return item.id; }, // 搜索列表中的显示ajax : {url: "test-api", // 异步请求地址dataType : "json", // 数据类型data: function (term, page) { // 请求参数(GET)return { q: term };},results: function (data, page) { return data; }, // 构造返回结果escapeMarkup : function (m) { return m; }// 字符转义处理}});
服务端(这里以 Laravel 为例)
Route::get('test-api', function () {$q = Input::get('q');// do something ...return array(// 'more' => false,'results' => array(array('id' => '北京', 'text' => 'bj beijin 北京'),array('id' => '厦门', 'text' => 'xm xiamen 厦门'),array('id' => '福州', 'text' => 'fz fuzhou 福州'),),);});