我正在尝试使用jquery,ajax和php从数据库进行实时搜索。获得结果后,我想从结果中选择选项设置输入字段的值。代码返回实时搜索结果,但没有将所选选项的值设置为输入字段。
<html>
<body>
<input type="text" id="search" placeholder="Search" />
<div class="display"></div>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
$(document).ready(function() {
$("#search").keyup(function() {
var searchid = $(this).val();
$.ajax({
type: "POST",
url: "result.php",
data: {
search: searchid
},
success: function(data) {
$(".display").html(data).show();
}
});
});
});
</script>
<script>
$(document).ready(function() {
$(".sel").click(function() {
var value = $(this).text();
$('#search').val(value);
});
});
</script>
</body>
</html>
<?php
$q = $_POST['search'];
$con = mysqli_connect("localhost", "root", "", "testing");
$query = "select name from test where name like '%$q%';";
$result = mysqli_query($con, $query);
while($row = mysqli_fetch_array($result, MYSQLI_ASSOC))
{
$name = $row['name'];
echo '<div class="sel">'.$name.'</div>';
}
?>