[英]JQuery UI Autocomplete, change event doesn't fire
我在 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
仍将包含旧值。
谢谢
注意:当我在选择后清除该字段但仍将焦点保持在该字段上时,它不起作用。
更新:我已报告的错误位置上bugs.jqueryui.com
当我运行您的代码片段时,每次选择项目或清除值时都会触发更改事件,并打印日志。 但是只有在我选择后退出,或者在自动完成输入元素之外单击后,才会触发该事件。
这是因为,根据文档,仅当元素失去焦点时才会触发更改事件。
使其工作的步骤:
您不必在自动完成选项中保持输入同步。 将单独的事件处理程序附加到您的文本输入,如下所示:
$("#txtAutocomplete").autocomplete({ source: ['test1', 'test2', 'test3'], select: function(event, ui){ console.log('select', ui.item.value); $("#hiddenField").val(ui.item.value); } }); $("#txtAutocomplete").on("input propertychange", function () { console.log("change", this.value); $("#hiddenField").val(this.value); });
<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> <input type="text" id="txtAutocomplete"> <input type="text" id="hiddenField" disabled="disabled">
我遇到了这个问题,有一个技巧可以避免这个问题。 你必须强制模糊,但使用 setTimeout
if(ui.item){
//console.log('select', ui.item.label);
$("#hiddenField").val(ui.item.id);
setTimeout(function () {
$(event.target).blur();
});
return ui.item.label;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.