此代码运行正常。但是,我需要帮助让“输入”标签像组合框一样显示。我试图将输入框设置为组合框,但没有成功。我也在寻找一种通过动态构建选项使代码与组合框一起工作的方法。感谢您提供任何帮助。
$(function () {
var availableTags = new Array(1000000);
var j = 0;
for (var i = 1; i < availableTags.length; i++) {
availableTags[j++] = i.toString();
}
$("#tags").autocomplete({
source: function (req, responseFn) {
var re = req.term;
var matcher = new RegExp("^" + re, "i");
var a = $.grep(availableTags, function (item) {
return matcher.test(item);
});
responseFn(a.slice(0, 5));
},
select: function (event, ui) {
if (ui.item && ui.item.value) {
var titleinput = ui.item.value;
ui.item.value = $.trim(titleinput);
alert(ui.item.value);
}
},
change: function (event, ui) {
if (!valid) {
// remove invalid value, as it didn't match anything
$(this).val("");
select.val("");
return false;
}
}
});
});
.custom-combobox {
position: relative;
display: inline-block;
border-style: solid;
border-width: 1px;
}
.custom-combobox-toggle {
position: absolute;
top: 0;
bottom: 0;
margin-left: -1px;
padding: 0;
}
.custom-combobox-input {
margin: 0;
padding: 5px 10px;
}
/*
.custom-combobox-list-item {
color: blue;
font-weight: bold;
}
.custom-combobox-input , .custom-combobox-list-item.ui-state-focus {
color: black;
font-weight: bold;
font-style: italic;
}
*/
#tags {
width: 40px;
}
<script type="text/javascript" src="https://code.jquery.com/jquery-1.11.1.min.js"></script>
<script type="text/javascript" src="https://code.jquery.com/ui/1.11.1/jquery-ui.min.js"></script>
<link rel="stylesheet" href="https://code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css">
<label for="tags">Tags: </label>
<input id="tags" type="text" class="custom-combobox" value="">
最佳答案
您可以使用 datalist
将选项传输到 text input
,然后将其转换为 combobox
我将您的代码精简到最基础的部分,以制作一个简单的示例。
<label for="tags">Tags: </label>
<input id="tags" name="tags" type="text" list="options" class="custom-combobox" value="">
<datalist id="options">
<!-- it puts the options here then the input type text gets them as select options -->
</datalist>
$(function () {
var availableTags = new Array(10);
var j = 0;
for (var i = 1; i < availableTags.length; i++) {
$('#options').append("<option value='" + i + "'>");
}
});
这是一个 JSFIDDLE 显示基本功能
关于javascript - 将输入框转换为组合框以实现 jQuery 自动完成,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/26128133/