我的自动填充的句子结构是:
<职业> <对于> <时间段>
例:
>学生5年
>老师2年
在数据库中,我有一个包含职业列表的列.使用jQuery UI自动完成,我使用以下代码填充文本输入中的前两个部分:
<script> $(function() { $("#occupation").autocomplete({ source: 'search.PHP',delay: 500,select: function(event,ui) { $(this).val(ui.item.value) } }); }); </script> <input type='text' name='occupation' id='occupation’>
<?PHP $searchTerm = $_GET['term']; $query = $db->query("SELECT DISTINCT occupation FROM table WHERE occupation LIKE '%" . $searchTerm . "%' ORDER BY occupation ASC"); $a_json = array(); while ($row = $query->fetch_assoc()) { $data_row["value"] = $row['occupation'] . ' for'; $data_row["label"] = $row['occupation']; array_push($a_json,$data_row); } echo json_encode($a_json);
现在,有没有办法创建第二个触发器来为其余的自动完成?就像选择职业一样,如果用户输入5,它将显示该时间段的以下自动完成选项:5天/ 5周/ 5个月/ 5年.如下图所示:
提前感谢您的建议.
我建议按照此处显示的多个示例:
http://jqueryui.com/autocomplete/#multiple
原文链接:/php/134943.html基本上,我们将有选择地选择要填写的标签,使用“for”作为分隔符而不是“,”.
var occupations = [{ value: "Assistant for",label: "Assistant" },{ value: "Student for",label: "Student" },{ value: "Teacher for",label: "Teacher" }]; var oLength = [ "Days","Weeks","Months","Years" ]; $(function() { function split(val) { return val.split(/\sfor/); } function extractLast(term) { return split(term).pop(); } $("#occupation").on("keydown",function(event) { if (event.keyCode === $.ui.keyCode.TAB && $(this).autocomplete("instance").menu.active) { event.preventDefault(); } }).autocomplete({ minLength: 0,source: function(request,response) { var term = extractLast(request.term); var results = []; if (request.term.indexOf("for") > 0) { var regE = /^(.*)\sfor\s(\d)\s(.*)$/ if (regE.test(request.term)) { return false; } if (parseInt(term) > 0) { $.each(oLength,function(k,v) { results.push(term + " " + v); }); } } else { results = $.ui.autocomplete.filter( occupations,request.term); } response(results); },focus: function() { // prevent value inserted on focus return false; },ui) { var terms = split(this.value); terms[0] = terms[0] + " for"; // remove the current input terms.pop(); // add the selected item terms.push(ui.item.value); // add placeholder to get the comma-and-space at the end terms.push(""); this.value = terms.join(""); return false; } }); });
<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css"> <script src="https://code.jquery.com/jquery-1.12.4.js"></script> <script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script> <input type="text" id="occupation" />