2012-04-19 80 views
0

我正在使用JQuery UI自动填充与ASP.NET文本框来填充标签以及值。这里是我从ajax调用映射数据的地方:JQuery UI自动完成替换标签的值选择

success: function (data) { 
    response($.map(data, function (item) { 
     return { 
      label: item.label, 
      value: item.value 
     } 
    })); 
} 

标签是文本,值是用于标识该行的数字。我的问题是,当用户选择一个选项时,文本框将用该值替换标签。因此,如果他们选择'John Smith',那么文本框会从'John Smith'更改为'1234'等。我如何操作select事件以将文本保留在文本框中?任何帮助表示赞赏。谢谢!

这里是我的aspx页面的更全面的观点:

<div class="ui-widget"> 
     <asp:TextBox ID="txbSearchKeyword" runat="server" Columns="50" /> 
    </div> 
    <asp:HiddenField ID="selectedRecordId" runat="server" /> 

和Jquery的:

(function() { 
    $("#txbSearchKeyword").autocomplete 
    ({ 
     source: 
      function (request, response) { 
       $.ajax({ 
        type: "POST", 
        url: "AutoComplete.asmx/GetAutoCompleteList", 
        contentType: "application/json; charset=utf-8", 
        data: JSON.stringify({ keywordStartsWith: request.term }), 
        dataType: "json", 
        success: function (data) { 
         response($.map(data.d, function (item) { 
          return { 
           label: item.label, 
           value: item.value 
          } 
         })); 
        } 
       }); 
      }, 
     minLength: 2 
    }); 

    $("#txbSearchKeyword").autocomplete 
    ({ 
     select: function (event, ui) { 
      $('#selectedRecordId').val(ui.item.value); 
      DoSomethingwithdataAJAXfunction(ui.item.value); 
     } 
    }); 
})(); 
+0

你可以发布剩余的jQuery和一些HTML吗?没有看到所有的代码就很难排除故障。 – 2012-04-19 16:06:17

+0

没问题!请参阅我的编辑。 – Drew 2012-04-19 16:45:53

回答

2

也许有些这个片段将帮助您:

select: function(event, ui) { 
    var hasValue = (ui.item.value != undefined && ui.item.value != "" && ui.item.value != null); 
    if (hasValue) { 
     var focusedElement = $(this); 
     focusedElement.val(ui.item.label); 
     return false; 
    } 
    else { 
     return false; 
    } 
}, 
focus: function(event, ui) { 
    return false; // return "true" will put the value (label) from the selection in the field used to type 
}, 

顺便说一句,我不知道为什么你的东西分开时:

minLength: 2 
}); 
    $("#txbSearchKeyword").autocomplete 
({ 
    select:... 

可能仅仅是:

minLength: 2, 
select:... 
+0

正是我需要的,谢谢!我不知道我可以用那种方式使用焦点事件。并感谢其他改进! – Drew 2012-04-19 18:25:15

0

value是将显示在文本字段变量。

所以你需要改变它。 label: item.value, value: item.label :)

+0

感谢您的回复!但这并不能帮助我,因为标签是自动完成建议列表中显示的内容。所以我的下拉菜单会显示所有的ID号码。 – Drew 2012-04-19 16:41:30

0

即时假设您想要选中的项目出现在

ID="txbSearchKeyword" 

this textbox?

尝试添加了此信息自动完成:

({ 
    select: function (event, ui) { 

    //add this --> $('#txbSearchKeyword').val(ui.item.label); 
     $('#selectedRecordId').val(ui.item.value); 
     DoSomethingwithdataAJAXfunction(ui.item.value); 
    } 
}); 

你可以尝试添加该行是注释。我今天遇到了同样的问题,并且为我工作。