Typeahead的使用总结
Typeahead是Bootstrap的自动补全JS插件。
最近项目中用到,总结一下。
与autocomplish类似,通过ajax实现,实现流程是前台输入关键字,后台根据关键字查询出信息,构造json串并返回,前台接收显示。
实例一
HTML代码:
<input type="text" class="form-control" id="employee_name" name="employee_name" data-provide="typeahead" placeholder="" autocomplete="off" disableautocomplete /> <input name="employee_id" type="hidden" value="" />
PHP部分代码:
$suggestions = array(); $i=0; $q = strtoupper($query); $sql = "SELECT employee_id,employee_name from employee as e where upper(e.employee_name) like '$q%'";
$data = $conn->getAll($sql)
foreach($data as $key=>$val) {
$suggestions[$i] = $val['name'];
$data[$i]['employee_id'] = $val['employee_id'];
$i++;
}
$ar = array('query'=>$query,'suggestions'=>$suggestions,'data'=> $data);
echo json_encode( $ar);
目的就是拼接json字符串,要求返回的格式类似:
{"query":"m","suggestions":["Mafei","MMFF"],"data":[{"employee_id":"1","name":"Mafei"},{"employee_id":"4","name":"MMFF"}]}
当输出m,查询出来的关键词是"Mafei","MMFF",选中一个后要将对应的id放到隐藏的文本框中,因为实际数据库中保存的是supplier_id。
JS代码:
$('#employee_name').keyup(function(){ $('#employee_id').val(0); }).typeahead({ source: function (query, process) { var parameter = {query: query}; $.get('ajax-typeahead.php?type=employee&profile=13', parameter, function (result) { var result = eval("(" + result + ")"); var data = result.data; objects = []; map = {}; $.each(data, function(i, object){ map[object.name] = object; objects.push(object.name); }); process(objects); }); }, updater: function(item){ $('#employee_id').val(map[item].employee_id); return item; } });
注意事项:
updater的意思是每次从关键词列表中选中值执行的操作。目的是获得每个employee_name对应的id.
实例二
有时页面中要多次使用typeahead。
如果有一个表格,每行中都有一个单元格要求值是从自动补全中获得的。
$('.typeahead').each(function(){ var aa = $(this); aa.typeahead({ source: function (query, process) { var parameter = {query: query}; $.get('ajax-typeahead.php?type=supplier', parameter, function (result) { var result = eval("(" + result + ")"); var data = result.data; labels = []; mapped = {}; $.each(data, function(i, item){ mapped[item.name] = item.supplier_id; labels.push(item.name); }); process(labels); }); }, updater: function(item){ aa.nextAll(".supplier_id").val(mapped[item]); return item; } }) })