문제

I'm working on a piece of code which has used jquery ui autocomplete component in order filter searched items. I have to configure it in order to be available to search based on multi ple factors, here is my sample search array:

    var availableTags = [{
    name: "Smith",
    family: "Johnson",
    account_number: "10032",
    nick_name: "Friend account",
    }, {
    name: "Susan",
    family: "Rice",
    account_number: "343243",
    nick_name: "Mom Account",
    }, {
    name: "Joe",
    family: "Austin",
    account_number: "3434",
    nick_name: "Partner Account",
    }, {
}];

the auto complete should display name, family, account number and nick_name when displaying the suggestion box. but when each item is selected only the account_number must be inserted into the text box. user must also be able to search through name, family, account number and nick name all of them. How can i achieve this target?

도움이 되었습니까?

해결책

You need to:

  • Revise the data array to contain the value parameter (this allows autocomplete to fill the input upon focus/select)
  • Write a custom source function that filters the data based on what user has typed
  • Write a custom _renderItem function that displays the data formatted to your liking

So you have:

var userData = [{
    name: "Smith",
    family: "Johnson",
    value: "10032",
    nick_name: "Friend account"
}, {
    name: "Susan",
    family: "Rice",
    value: "343243",
    nick_name: "Mom Account"
}, {
    name: "Joe",
    family: "Austin",
    value: "3434",
    nick_name: "Partner Account"
}];
$("#autocomplete").autocomplete({
    source: function (request, response) {
        var search = $.trim(request.term.toLowerCase());
        var array = $.grep(userData, function (val) {
            return
                val.name.toLowerCase().indexOf(search) >= 0 ||
                val.family.toLowerCase().indexOf(search) >= 0 ||
                val.value.toLowerCase().indexOf(search) >= 0 ||
                val.nick_name.toLowerCase().indexOf(search) >= 0;
        });
        response(array);
    }
})

.data("ui-autocomplete")._renderItem = function (ul, item) {
    var $a = $("<a></a>").text(item.name + " " + item.family);
    $("<br />").appendTo($a);
    $("<small></small>").text(item.nick_name).appendTo($a);
    $("<br />").appendTo($a);
    $("<small></small>").text(item.value).appendTo($a);
    return $("<li></li>").append($a).appendTo(ul);
};

Demo here

라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top