【问题标题】:Jquery UI autocomplete event changeJquery UI 自动完成事件更改
【发布时间】:2013-05-31 15:50:34
【问题描述】:

您好,我遇到了更改事件的问题。 通过文档应该有对象 ui.item

选择一个项目后; ui.item 是指选中的项目。总是在关闭事件之后触发。

但是当我尝试它时 ui.item 是未定义的 :( 当自动完成中的输入与脚本中的数据不匹配时,我想取消设置 s_town_id。

<input id="s_town" type="text" name="s_town" />
<input type="text" id="s_town_id" name="s_town_id"  />
$(function() { $("#s_town").autocomplete({ source: function(request, response) { $.ajax({ url: "/_system/_ajax/uiautocomplete.php", dataType: "json", data: { name: "s_town", term: request.term }, success: function(data) { response($.map(data, function(item) { return { label: item.whisper_name+ " [" + item.zip_code + " / " + item.lup_state + "]", value: item.whisper_name, id: item.whisper_id, zip_code: item.zip_code, lup_state: item.lup_state, stateid: item.stateid } })) } }) }, minLength: 2, select: function(event, ui) { $("#s_town_id").val(ui.item.id); }, change: function(event, ui) { // ui.item is undefined :( where is the problem? $("#s_town_id").val(ui.item.id); } }); });

【问题讨论】:

  • 嘿 Stenly,我遇到了完全相同的问题,并且不得不使用相同的解决方法。您能找到更好的解决方案吗?
  • hmm 意识到问题在于我从教程中加载了源代码,该教程的 ui 版本为 1.8,对于最终遇到此问题的任何人,此问题已在 1.8.11 中修复。 bugs.jqueryui.com/ticket/5490

标签: jquery-ui autocomplete


【解决方案1】:

我找到了我测试 event.originalEvent.type 的解决方案,如果它是meneuselected 与否,失败后我取消设置 s_town_id。 但是任何更好的解决方案仍然是受欢迎的。

<input id="s_town" type="text" name="s_town" />
<input type="text" id="s_town_id" name="s_town_id"  />
$(function() { $("#s_town").autocomplete({ source: function(request, response) { $.ajax({ url: "/_system/_ajax/uiautocomplete.php", dataType: "json", data: { name: "s_town", term: request.term }, success: function(data) { response($.map(data, function(item) { return { label: item.whisper_name+ " [" + item.zip_code + " / " + item.lup_state + "]", value: item.whisper_name, id: item.whisper_id, zip_code: item.zip_code, lup_state: item.lup_state, stateid: item.stateid } })) } }) }, minLength: 2, select: function(event, ui) { $("#s_town_id").val(ui.item.id); }, change: function(event, ui) { try { if(event.originalEvent.type != "menuselected") { // Unset ID $("#s_town_id").val(""); } } catch(err){ // unset ID $("#s_town_id").val(""); } } }); });

【讨论】:

    【解决方案2】:

    如果 ui.item 未定义,则意味着您的 json 源格式不正确。 你必须像这样发送一个 json 源:

    [{"label":"Jean","value":1},{"label":"carl","value":2}]
    

    您可以向数组添加更多键,但至少您必须设置“标签”和“值”。 检查 json 字符串。 我也认为你目前使用最新版本的自动完成 1.8.1

    【讨论】:

    • 是的,但是当输入值与数据库中的任何记录都不匹配时,我想要解决方案。所以在那一刻 JSON 是空的。我想要的功能可以描述为必须匹配。
    猜你喜欢
    • 2015-03-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2014-02-14
    • 1970-01-01
    • 2011-09-19
    • 2011-07-06
    相关资源
    最近更新 更多