Jquery UI自动完成事件更改

时间:2010-05-12 15:35:11

标签: jquery-ui autocomplete

嗨,我遇到了变更事件的问题。 通过documntation应该有对象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);
   }

  });


 });
    


2 个答案:

答案 0 :(得分:6)

我找到了测试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("");
    }
   }

  });


 });
    


答案 1 :(得分:0)

如果未定义ui.item,则表示您的json源格式不正确。 您必须发送这样的json源:

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

您可以为数组添加更多键,但至少必须设置“label”和“value”。 检查json字符串。 另外我估计你现在使用最新版本的自动完成1.8.1