EasyUI combobox下拉列表实现搜索过滤(模糊匹配)和placeholder效果

实现搜索功能:  

项目中的某个下拉列表长达200多个项,这么巨大的数量一个一个找眼镜都得看花,因而就得整了个搜索功能。看网上别人帖子有只能前缀匹配的方案,但只能前缀匹配的话用起来也不是很方便。因而就记录一下模糊匹配的方案。函数

实现效果:ui

这里使用的是combobox组合框,对于combobox的建立能够使用<input>输入框,也能够使用<select>下拉选。我使用的是<select>:this

HTML代码url

<label>关联课程</label>
<select class="easyui-combobox" name="itemsId" id="itemsId" style="width:135px;height:25px;">
    <option>请选择关联课程</option>
</select>

而后经过js从远程获取数据并实现搜索功能:spa

$("#itemsId").combobox({ url: "xxxxxx", editable: true, valueField: 'id', textField: 'name', panelWidth: 220, // 下拉框宽度 panelHeight: 250, // 下拉框高度 filter: function(q, row){ var opts = $(this).combobox('options'); return row[opts.textField].indexOf(q) > -1; } }); 

由于须要输入查询,因此下拉项必须得可编辑。使用combobox建立下拉项默认是能够编辑的,设置 editable: true 虽然感受很鸡肋,但看起来功能更清晰。code

filter:定义函数如何过滤数据,return row[opts.textField].indexOf(q) == 0时只能前缀匹配,  return row[opts.textField].indexOf(q) > -1 就是模糊匹配了。
orm

 

  这样模糊匹配的功能就实现了。随便记录一下默认显示值的问题。blog

设置显示默认值:

实现placeholder效果

使用combobox组合框时,会生成 class=“combo-text validatebox-text” 的文本框,因此经过id和类选择器选择目标input设置placeholder属性便可。事件

经过id定位时,不能使用combobox的id,得使用父级元素的id定位input

<div id="subCourse_dlg" style="width: 300px; height: 160px;" closed="true">    
    <div style="margin: 10px 10px;">
        <select class="easyui-combobox" name="subCourse" id="subCourse" style="width: 220px;">
        </select>
    </div>
 </div>

$("#subCourse_dlg .combo-text").attr("placeholder","选择或输入名称查询...");

显示默认值

在修改数据时默认得显示设置的值,也就是加载的选择项selected=true,一开始我是想使用formatter函数将获取的列表数据选中的项添加selected属性为true,但这种方式会致使下拉列表显示为空白

 

因此这种方式是不可行的,因而就寻求了其余方式,发现了解决方案:

经过combobox的select方法:

只需添加下面这行代码就行,在combobox建立先后均可以。

$("#itemsId").combobox("select", rows.name)

这是经过combobox的select方法选择指定的选项,“rows.name”能够是option的value,也能够text。

固然也能够在combobox的onLoadSuccess事件,从远程数据加载成功时处理(这种方式就太累赘了,只是为了记录一下onLoadSuccess的使用):

$("#itemsId").combobox({ url: 'xxxx', editable: true,  valueField: 'id', textField: 'kcName', panelWidth: 220, panelHeight: 250, filter: function(q, row){ var opts = $(this).combobox('options'); return row[opts.textField].indexOf(q) > -1; }, onLoadSuccess: function(data) { for(var i = 0; i < data.length; i++) { if(data[i].id == rows.itemsId) { $("#itemsId").combobox("select", data[i].id) } } } }); 
相关文章
相关标签/搜索