我有两个输入来搜索同一个数据库表。使用下面的代码,两个输入都正确搜索,但都显示第一个输入字段下的结果div。我需要第二个结果div出现在第二个输入下,而不是第一个。希望这是有道理的。
搜索-form.php的:
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function(){
$('.search-box input[type="text"]').on("keyup input", function(){
/* Get input value on change */
var inputVal = $(this).val();
var resultDropdown = $(this).siblings(".result");
if(inputVal.length){
$.get("backend-search.php", {term1: inputVal}).done(function(data){
// Display the returned data in browser
resultDropdown.html(data);
});
} else{
resultDropdown.empty();
}
});
// Set search input value on click of result item
$(document).on("click", ".result p", function(){
$(this).parents(".search-box").find('input[type="text"]').val($(this).text());
$(this).parent(".result").empty();
});
});
</script>
</head>
<body>
<form id="tcalc" name="tcalc">
<div class="search-box" style="white-space: nowrap;">
<!-- Search origin zip /-->
<input type="text" autocomplete="off" id="ozip" name="ozip" placeholder="Search Origin ZIPCode..." onclick="this.select();" autofocus /> </nobr>
<!-- Search destination zip /-->
<input type="text" autocomplete="off" id="dzip" name="dzip" placeholder="Search Destination ZIPCode..." onclick="this.select();"/> </nobr>
<!-- Dropdwon of results /-->
<div class="result"> </div>
</div>
</form>
</body>
后端-search.php中:
// Escape user inputs for security
$term = mysqli_real_escape_string($link, $_REQUEST['term']);
if(isset($term)){
// Attempt select query execution if numeric
if (is_numeric($term)) {
$sql = "SELECT CONCAT(trim(zipcode),' | ',trim(pcity),', ',trim(state)) as 'result' from `tbl_uscomp_i` WHERE `zipcode` LIKE '" . $term . "%'";
}
// Attempt select query execution if alpha
if (ctype_alpha($term)) {
$sql = "SELECT CONCAT(trim(zipcode),' | ',trim(pcity),', ',trim(state)) as 'result' from `tbl_uscomp_i` WHERE `pcity` LIKE '" . $term . "%'";
}
// Fetch results if results are indeed found
if($result = mysqli_query($link, $sql)){
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_array($result)){
echo "<p>" . $row['result'] . "</p>";
}
// Close result set
mysqli_free_result($result);
} else {
echo "<p>No matches found</p>";
}
} else {
echo "ERROR: Could not able to execute $sql. " . mysqli_error($link);
}
}
// Close connection
mysqli_close($link);
我还有第二个问题,关于如何通过下拉结果允许键盘输入(箭头和输入/选择)......
代码改编自here