gpt4 book ai didi

javascript - 单击结果后如何清除实时 ajax 搜索中的输入字段空白

转载 作者:行者123 更新时间:2023-12-03 04:09:54 25 4
gpt4 key购买 nike

我有一个使用 PHP jQuery 和 ajax 的简单 ajax 实时搜索脚本。一切都很好,但输入框没有完全清除,因此结果框不会消失,除非我手动清除它..

JS-

<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", {term: 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", function(){
$(this).parents(".search-box").find('input[type="text"]').val($(this).text());
$(this).parent(".result").empty();

});
});
</script>

PHP-

$user = $_GET['user'];

$term = mysqli_real_escape_string($conn, $_REQUEST['term']);
if(isset($term)){
// Attempt select query execution
$sql = "SELECT * FROM prospects WHERE dealer_name LIKE '" . $term . "%'";
if($result = mysqli_query($conn, $sql)){
if(mysqli_num_rows($result) > 0){
while($row = mysqli_fetch_array($result)){
$dealer_name = $row['dealer_name'];
echo "<form method='post' class='editForm'>
<input type='hidden' name='dealer' value='$dealer_name'/>
<input type='submit' id='subDealer' value='$dealer_name'/>
</form>";
}
// Close result set
} else{
echo "<p>No matches found</p>";
}
} else{
echo "ERROR: Could not able to execute $sql. " . mysqli_error($conn);
}
}

HTML -

 <div class="search-box">
<input type="text" id="searchBox" autocomplete="off" placeholder="Search dealer..." />
<div class="result"></div>
</div>

就像它说的那样,一切正常,但输入字段(#searchBox)中有空白,这将不允许清除.result..

谢谢!

最佳答案

尝试下面的代码片段

// Set search input value on click of result item
$(document).on("click", ".result", function(){
$(this).parents(".search-box").find('input[type="text"]').val($(this).text().trim());
});


$(document).on('click', 'input[type=submit]', function() {
// This is NOT the best practice. But it works. Try to change your implementation to a better one!
setTimeout(function() {
$('.result').empty();
}, 1000);
return true;
}

关于javascript - 单击结果后如何清除实时 ajax 搜索中的输入字段空白,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44373798/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com