Ash*_*nko 7 php jquery jquery-ui autocomplete
我的自动填充的句子结构是:
<Occupation> <for> <time period>
例:
在数据库中,我有一个包含职业列表的列.使用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’>
Run Code Online (Sandbox Code Playgroud)
该search.php代码:
<?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);
Run Code Online (Sandbox Code Playgroud)
现在,有没有办法创建第二个触发器来为其余的自动完成?就像选择职业一样,如果用户输入5,它将显示该时间段的以下自动完成选项:5 days/ 5 weeks/ 5 months/ 5 years.如下图所示:

提前感谢您的建议.
Twi*_*sty 10
我建议按照此处显示的多个示例进行操作:http://jqueryui.com/autocomplete/#multiple
基本上,我们将选择性地选择要填写的标签," 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;
},
select: function(event, 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;
}
});
});Run Code Online (Sandbox Code Playgroud)
<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" />Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1308 次 |
| 最近记录: |