$("#search").on("keyup", function() {
//to call ajax
//remoteSearch();
//or static search
var v = this.value.replace(/\s+/g, " ").trim().toLowerCase();
if (v == "") return $(".option").hide();
$(".option").hide();
$(".option").each(function() {
var t = $(this).text().toLowerCase();
if (t.indexOf(v) > -1) $(this).show();
});
});
$(document).on("click", ".option", function() {
$("#search").val($(this).text());
$(".option").hide();
});
function remoteSearch() {
$.ajax({
url: "data.php",
data: {
"search": $("#search").val() //search box value
},
dataType: "json", // recommended response type
success: function(data) {
//data = ["name1","name2","name3"];
$(".options").html(""); //remove list
$.each(data, function(i, v) {
$(".options").append("<li class='option'>" + v + "</li>");
});
},
error: function() {
alert("can't connect to db");
}
});
}
#search {
padding: 5px;
}
#select-containe {
width: 200px;
}
.option {
padding: 5px;
display: none;
color: white;
background: orange;
cursor: hand;
}
.option:hover {
color: orange;
background: white;
}
.options {
height: 100px;
width: 190px;
overflow: auto;
padding: 0;
margin: 0;
display: absolute;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='select-container'>
<input id='search' placeholder='search names' />
<ul class='options'>
<li class='option'>Mohamed</li>
<li class='option'>Ahmed</li>
<li class='option'>Mahmoud</li>
<li class='option'>Mustafa</li>
<li class='option'>mohamed</li>
<li class='option'>ahmed</li>
<li class='option'>mahmoud</li>
<li class='option'>mustafa</li>
</ul>
</div>
choose names from above list
不知道你是問。 – wongcode
成爲選擇是強制性的嗎?這可能是一個自動完成的輸入框?你能提供關於數據綁定的更多代碼嗎? –