gpt4 book ai didi

javascript - Jquery 未获取最新输入值

转载 作者:行者123 更新时间:2023-11-28 00:06:43 25 4
gpt4 key购买 nike

目前,我正在创建一个搜索栏。无论如何,我正在抓取输入值,但问题是它并不总是抓取我想要它抓取的内容。让我再解释一下。

我遇到问题的地方是当我用下拉值更新输入值时。我将在之后进入代码,但只需在查询中提交文本时,它只会获取用户输入的内容。因此,如果用户点击下拉值,它不会提交该值,它只会提交用户出于某种原因输入的内容。

<小时/>

编码时间!!!

HTML

<input type="text" name="search" class="col-xs-8 col-xs-offset-1 col-sm-5 col-sm-offset-3" id="searchbar" autocomplete="off" value="<?php echo $query; ?>"/>
<button class="glyphicon glyphicon-search glyphicon-non-button col-xs-2 col-sm-1" id="searchbarbutton" input type="submit"> </button>
<div class="col-xs-8 col-xs-offset-1 col-sm-5 col-sm-offset-3" id="postsearchsuggestionholder">
<div class="postsearchsuggestion col-xs-12" id="postsearchsuggestion1"></div>
</div>

Javascript(还有 Jquery)

//Adds the Query to the URL

$("[name='searchform']").change(function() {
$("[name='searchform']").attr("action", "http://localhost/postin'/categories/<?php echo $category; ?>/" + $("#searchbar").val().trim());
});

//Removes the dropdown
$("#searchbar").keyup(function() {
if ($("#searchbar").val().length == 0) {
$("#postsearchsuggestionholder").hide();
$('#searchbar').css("border-bottom-left-radius","3px");
}
});

//Dropdown stuff (Autocomplete stuff)
$(function() {
$("#searchbar").autocomplete({
source: function(request,response) {
$.ajax({
url: "http://localhost/postin'/categories/searchbar.php",
dataType: "json",
type: "POST",
data: { 'keyword': request.term,
'category': "<?php echo strtolower($category); ?>" },
success: function(data) {
if (0 in data) {
$('#postsearchsuggestionholder').show();
$('#searchbar').css("border-bottom-left-radius","0px");
$('#postsearchsuggestion1').text(data[0]);
$('#postsearchsuggestion1').show();
}
else {
$('#postsearchsuggestion1').hide();
}
$("#postsearchsuggestion1").click(function() {
$('#searchbar').val(data[0]);
$('#postsearchsuggestionholder').hide();
$('#searchbar').css("border-bottom-left-radius","3px");
});
}
});
},
});
});
<小时/>

很简单,如果用户输入 hel 那么它可能会建议 hello,但它仍然会搜索 hel ,我不知道为什么。有任何想法吗?谢谢!

<小时/>

已编辑缩短了代码。

最佳答案

我很确定答案在于 val() 不会触发 change 事件。试试这个:(注意第二行已与您的不同)

...
$("#postsearchsuggestion1").click(function() {
$('#searchbar').val(data[0]).trigger("change");
$('#postsearchsuggestionholder').hide();
$('#searchbar').css("border-bottom-left-radius","3px");
});
...

关于javascript - Jquery 未获取最新输入值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31281849/

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