我正在进行Ajax驱动的实时搜索。但现在我想点击下拉列表来填充html文本框。如何修改我的代码以包含一个功能,用户可以使用向上/向下箭头键滚动结果列表。这是JavaScript代码。
<script type="text/javascript">
function fill(Value) {
$('#name').val(Value);
$('#display').hide();
}
$(document).ready(function() {
$("#name").keyup(function() {
var name = $('#name').val();
if (name == "") {
$("#display").html("");
} else {
$.ajax({
type: "POST",
url: "ajax.php",
data: "name=" + name,
success: function(html) {
$("#display").html(html).show();
}
});
}
});
});
以下是ajax.php
页面
if(isset($_POST['name'])) {
$name=trim($_POST['name']);
$query=mysqli_query($con,"SELECT * FROM mobile WHERE name LIKE '%$name%' LIMIT 0,5");
echo "<ul>";
while($query2=mysqli_fetch_array($query))
{ ?>
<div class="ajaxcontainer">
<li onclick='fill("<?php echo $query2[' name ']; ?>")'>
<a href="preview.php?id=<?php echo $query2['name']; ?>">
<div class="ajaximage">
<img src="<?php echo $query2['photo'];?>">
</div>
<div class="ajaxh1">
<h1><?php echo $query2['name']; ?></h1>
</div>
</a>
</li>
</div>
<?php } } ?>
答案 0 :(得分:0)
好消息..工作3个小时后......我得到了你问题的解决方案。检查解决方案。如果您在此解决方案中遇到任何问题,请告诉我。我
<!DOCTYPE html>
<html>
<body>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.2.0/jquery.min.js"></script>
<style type="text/css">
ul{
position: absolute;
top: 5px;
left: 36px;
list-style: none;
}
li{
border: 1px solid grey;
width: 202px;
margin: 0px;
}
input{
width:200px;
}
</style>
<script>
function showHint(str){
if(str=="" || !str){
$("ul").empty();
return;
}
$.ajax({
type: "GET",
url: "gethint.php",
data: "q="+str,
success: function(html) {
var names = html.split(",");
var listItems ="";
var dropDown =$("#dropDown");
dropDown.innerHTML="";
$("ul").empty();
names.forEach(name =>{
var li = document.createElement("li");
li.appendChild(document.createTextNode(name));
dropDown.append(li);
$("li").click(function(){
$("#txt1").val($(this).text());
});
});
}
});
}
</script>
<h3>Start typing a name in the input field below:</h3>
<form action="">
<div style="position:relative">
First name: <input type="text" id="txt1" onkeyup="showHint(this.value)">
<ul id="dropDown"></ul>
</div>
</form>
</body>
</html>
这是我的php文件。
<?php
require("connection.php");
$sql ="SELECT name FROM users";
$a=array();
// OR $a=[];
$result=$conn->query($sql);
if($result->num_rows > 0){
while($row = $result->fetch_assoc()){
$a[]=$row["name"];
//echo $row["name"];
}
}
else{
echo "No data to generate suggestions";
}
// get the q parameter from URL
$q = $_REQUEST["q"];
$hint = "";
// lookup all hints from array if $q is different from ""
if ($q !== "") {
$q = strtolower($q);
$len=strlen($q);
foreach($a as $name) {
if (stristr($q, substr($name, 0, $len))) {
if ($hint === "") {
$hint = $name;
} else {
$hint .= ", $name";
}
}
}
}
?>