需要Jquery UI Autocomplete来解析对象而不是数组

时间:2014-11-07 15:21:50

标签: jquery jquery-ui object jquery-autocomplete jquery-ui-autocomplete

我想将id附加到员工姓名,因此我创建了一个对象而不是数组,但只填充了带有名称而不是id的自动完成字段。 jQuery Autocomplete参数param解析数组。我可以解析一个object.element吗?这是一些代码(需要更多的问题)。这可能吗?

$.ajax({
    type: 'get',
    url: 'xml/employeeList.xml',
    error: function(xhr, status, error) {alert('Could Not Retrieve Name List: '+xhr+', '+status+', '+error)},
    dataType: 'xml'
}).done(function(employees) {
    var empList = []; // array of objects
    $(employees).find('employeeList').children().each(function(index, element) {
        var $elm = $(this),
        first = $elm.find('first').text(),
        last = $elm.find('last').text(),
        lanID = $elm.find('lanID').text();
        empList.push({ // obj having label and value properties.
            value: lanID,
            label: first+' '+last
        });
    });
    console.log(empList);
    $("#tags").autocomplete({
        source: empList
    });
});

用户从自动完成中选择一个名称后,我需要将具有所选名称的对象中的员工lanID发送回Web服务。在此示例中,它不会将返回的lanID指定为id。 id最终看起来像这样(id =" ui-id-345")。我需要id为this(id ="无论返回的lan id是")

选择名称后,会显示LanID而不是名称。不是我想要的效果。我仍然希望它显示名称,但将lanID指定为输入或任何属性的id。

1 个答案:

答案 0 :(得分:1)

jQuery ui autocomplete还接受具有标签 value 属性的对象数组。因此,如果您还要包含 id 并根据 name 搜索值,则可以将名称指定为 label 属性的值和id作为value property的值。

以下几行:

$.ajax({
  type: 'get',
  url: 'xml/mockNameList.xml',
  error: function(xhr, status, error) {alert('Could Not Retrieve Name List: '+xhr+', '+status+', '+error)},
  dataType: 'XML'
}).done(function(employees) {
  var empList = []; // array of objects
  $(employees).find('employeeList').children().each(function(index, element) {
    var $elm = $(this),
    first = $elm.find('first').text(),
    last = $elm.find('last').text(),
    lanID = $elm.find('lanID').text();
    empList.push({ // obj having label and value properties.
      label: first+' '+last,
       value: lanID;
    });
  });
  $("#tags").autocomplete({
    source: empList
  });
});

如果传递具有标签属性的对象数组,则将根据标签进行搜索,这是名称每当您选择一个项目时,传递给回调函数的第二个参数(ui)将包含一个 item 属性,其值是与所选项目对应的对象。因此,您可以访问相关值,例如id,如ui.item.value


旁注:

请注意以下内容确定您要实现的目标:

empList[index] = 'name: "'+first+' '+last+'",lanID: "'+lanID;

在您的代码中empList是一个对象,而不是一个数组。它将数据存储为键值对,而不是基于索引。以上内容可能会产生以下形式的对象:

{
  "0": "name:Sir foo,lanID: 007",
  "1": "name:Sir bar',lanID: 008",
}

这对于自动完成以及其他任何内容都没用,因为 name lanID 等是字符串的一部分,您无法通过键名访问它们相反,你必须做字符串操作。此外,迭代对象时无法保证顺序。