gpt4 book ai didi

javascript - 从自动完成的输入框中获取选定的字符串

转载 作者:行者123 更新时间:2023-12-01 02:23:01 25 4
gpt4 key购买 nike

我正在构建一个表单,其中第一个字段(文本输入)是从 MySQL 表自动完成的,第二个字段(下拉列表)是根据第一个字段中所做的选择而填充的。自动完成工作正常,但我不知道如何从中获取所选选项;相反,我只获取我实际输入的搜索字符串(例如,“eggn”而不是我选择的“Eggnog”选项);事实上,“onchange”函数在所选选项被复制到输入框之前就触发了。

非常感谢对此的一些帮助。

<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script>
<script type="text/javascript">
$(document).ready(function () {
$("#name").autocomplete({
source: 'getautocomplete.php',
minLength: 2
});
});

function ajaxfunction(key) {
alert(key);
$.ajax({
url: 'get_units1.php?key=' + key,
success: function (data) {
$("#sub").html(data);
}
});
}
</script>

<form method="post">
<input type='text' id='name' onchange="ajaxfunction(this.value)">
<select id="sub">
<option value="">Choose the amount</option>
</select>
<input type='submit'>
<input type='reset'>
</form>

最佳答案

为了启用自动完成功能,我使用了一个虚拟数组作为自动完成的源。

如果我正确理解你的问题,绑定(bind)事件=select会比change更好。

以下代码的自动完成功能运行良好。您可以在代码片段中尝试测试用例,然后注意 changeselect 事件何时被触发。

事件=change将在失去焦点时触发。

当选择一项自动完成时,将触发事件=select

更新:感谢 @IncredibleHat 的评论,当已经引用 JQuery UI 时,我们应该摆脱 onchange="onChangeAutocomplete(this.value)"

<link rel="stylesheet" href="//code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script type="text/javascript">
var availableTags = [ "ActionScript","AppleScript","Asp","BASIC","C","C++","Clojure","COBOL","ColdFusion","Erlang","Fortran","Groovy","Haskell","Java","JavaScript","Lisp","Perl","PHP","Python","Ruby","Scala","Scheme"
];
$(document).ready(function(){
$("#name").autocomplete({
source: availableTags,
select: function( event, ui ) {
console.log('[select]the string in autocomplete: ' + ui.item.label + '-' + ui.item.value);
},
//As the comment from @IncredibleHat, get rid of using old way to bind onchange.
//follow the instructions of Jquery UI Autocomplete to bind the event like below
change: function( event, ui) {
console.log('[change1]the string in autocomplete: ' + ui.item.label + '-' + ui.item.value);
}
});
});

function onChangeAutocomplete(key)
{
console.log('[change2]the string in autocomplete: ' + key);
/*$.ajax({
url: 'get_units1.php?key=' + key,
success: function(data) {
$("#sub").html(data);
}
});*/
}

</script>

<form method="post">
<input type='text' id='name'" onchange="onChangeAutocomplete(this.value)">
<select id="sub">
<option value="">Choose the amount</option>
</select>
<input type='submit'><input type='reset'>
</form>

关于javascript - 从自动完成的输入框中获取选定的字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49055217/

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