Issue with custom properties in jQuery UI Autocomplete

无人久伴 提交于 2019-12-12 14:48:17

问题


I'm running into an issue with custom properties while using jQuery UI's autocomplete functionality. For some strange reason, the autocomplete function will not allow me to use the make or id attribute for ui.item.make or ui.item.id, but is working when it is set to ui.item.label.

Here is JSFiddle with an example of the issue I am encountering. Here is another example of where autocomplete is working, but the difference is only the label property.

Any information why using a custom property doesn't work for me would be greatly appreciated.


回答1:


You could simply pre-process the list of makes (see the forEach) - IF you get your data via ajax, you could also do something similar. NOTE: I also added return false to your select so it would not use the value and use your make instead.

var carMake = [{
    "make": "Smart",
        "id": '200038885'
}, {
    "make": "Bomb",
        "id": '200038885'
}, {

    "make": "Volkswagen",
        "id": '200000238'
}];

function addlabel(row) {
    row.label = row.make;
    row.value = row.id;
}
carMake.forEach(addlabel);
$("#vehicle_make").autocomplete({
    source: carMake,
    delay: 0,
    minLength: 1,
    autoFocus: false,
    select: function (event, ui) {
        $(this).val(ui.item.make);
        return false;
    }
});

EDIT: Ajax data note: to process using ajax data, this would be a method:

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



回答2:


I believe the default recognized properties only include label and value. If you want to use custom properties you need to implement the custom data property.

Would look something like this:

$("#vehicle_make").autocomplete({
    source: carMake,
    delay: 0,
    minLength: 1,
    autoFocus: false,
    select: function(event, ui) {
      $('#vehicle_make').val(ui.item.make);
    }
  })
  .data( "ui-autocomplete" )._renderItem = function( ul, item ) {
      return $( "<li>" )
        .append( "<a>" + item.make+ "<br>" + item.id + "</a>" )
        .appendTo( ul );
    };

Or via jsfiddle

That should allow you to access the ui.item object with custom properties.
(If you don't want id visible you could just hide it with a hidden field in the list item)

See http://jqueryui.com/autocomplete/#custom-data.




回答3:


According to the API documentation:

Array: An array can be used for local data. There are two supported formats: ...

An array of objects with label and value properties: [ { label: "Choice1", value: "value1" }, ... ]

So, it requires them to be specifically named like this.



来源:https://stackoverflow.com/questions/15908247/issue-with-custom-properties-in-jquery-ui-autocomplete

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!