我的 JQuery 自动完成有一些问题,我的代码如下:
var mySource = [{"label":"Value one","id":"1"},{"label":"Value two","id":"2"},{"label":"Value three","id":"3"}];
$("#txtAutocomplete").autocomplete({
source: mySource,
select: function(event, ui){
if(ui.item){
//console.log('select', ui.item.label);
$("#hiddenField").val(ui.item.id);
return ui.item.label;
}
else{
//console.log('select with null value');
$("#hiddenField").val('');
}
},
change: function(event, ui){
if(ui.item){
//console.log('change', ui.item.id);
$("#hiddenField").val(ui.item.id);
}
else{
//console.log('change with null value');
$("#hiddenField").val('');
}
}
});
<link href="https://code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css" rel="stylesheet" type="text/css" />
<script src="https://code.jquery.com/jquery-1.11.3.js"></script>
<script src="https://code.jquery.com/ui/1.11.4/jquery-ui.js"></script>
<p>
<ol>
<li>Type 'Value' in the text box</li>
<li>Press 'arrow down' to select the first element</li>
<li>Press enter</li>
<li>Keep pressed backspace to delete completely the selected item</li>
<li>Press TAB</li>
<li>Value in 'readonly' field is still there</li>
</ol>
</p>
<input type="text" id="txtAutocomplete">
<input type="text" id="hiddenField" disabled="disabled">
<button>Button added just to have an element to focus on</button>
当我将字符串“value”放入可编辑字段时,自动完成功能会正确显示,因此我可以选择一个值并将其放入 ID 为 hiddenField
的文本框中。
然后,如果我清除文本框中的值,则无法使用空白值更新相关的 hiddenField
,因为 change
事件不会触发。为什么?
测试代码片段的步骤:
- 在可编辑字段中写入“值”
- 选择一个值
- 清除所选值
hiddenField
仍将包含旧值。
谢谢
注意:当我在选择后清除该字段但仍将焦点保留在该字段上时,它不起作用。
更新:我报告了该错误 here在 bugs.jqueryui.com 上
最佳答案
我遇到了这个问题,并且有一个 hack 可以避免这个问题。您必须强制模糊,但使用 setTimeout
if(ui.item){
//console.log('select', ui.item.label);
$("#hiddenField").val(ui.item.id);
setTimeout(function () {
$(event.target).blur();
});
return ui.item.label;
}
关于javascript - JQuery UI 自动完成,更改事件不会触发,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42931996/