无论输入条目如何,jQuery自动完成都会建议所有选项

时间:2016-05-11 16:01:56

标签: javascript jquery json autocomplete

我有一个jQuery脚本,它将获得JSON响应并创建尽可能多的"播放器"响应中的对象。

然后它会添加到availablePlayers,然后我将其用作source:的{​​{1}}字段的变量

当用户选择一个玩家名称并点击"添加"按钮,此刻,只显示播放器的autocompleteguid

然而,无论我输入什么字母,所有玩家都可以选择。为了说明这一点,如果我输入" Z"并且没有一个玩家在他们的名字中有Z,他们的选项仍然显示。

如何改进此功能?

HTML

name

的jQuery

<div class="player-widget">
    <label for "players">Players</label>
    <input id="player" />
    <input id="playerGUID" hidden />
    <button id="add">Add</button>
</div>

示例JSON响应

$(document).ready(function(){

var availablePlayers = []; // BLANK ARRAY OF PLAYERS

$("#player").autocomplete({
    source: availablePlayers,
    response: function (event, ui) {
        ui.content = $.map(ui.content, function(value, key) {
            return {
                label: value.name,
                value: value.guid
            }
        });
    },
    focus: function(event, ui) {
        $("#player").val(ui.item.label);
        return false;
    },
    select: function (event, ui) {
        $("#player").val(ui.item.label); // display the selected text
        $("#playerGUID").val(ui.item.value); // save selected id to hidden input
        return false;
    }
});

$.getJSON("http://localhost/Websites/Player-Widgets/service.php", function(data) {

    var feedHTML = '';
    // LOOP THROUGH EACH PLAYER
    $.each(data.players, function(i, player) {

        // DEFINE VARIABLES - BASED ON PLAYER ATTRIBUTES
        var guid = player.guid;
        var name = player.name;
        var dob = player.date_of_birth;
        var birth = player.birthplace;
        var height = player.height;
        var weight = player.weight;
        var position = player.position;
        var honours = player.honours;

        // CREATE NEW PLAYER (OBJECT)
        var player = {
            guid: guid,
            name: name,
            position: position
        };

        // ADD TO PLAYER TAG ARRAY
        availablePlayers.push(player);
    });

    console.log("User friendly array");
    $.each(availablePlayers, function(i, val) {
        console.log(val.guid + " - " + val.name + " [" + val.position + "]");
    });

    console.log("Array printout");
    console.log(JSON.stringify(availablePlayers));

}).done(function(){
    console.log("Done! Success!");
    $("#player").autocomplete("option", "source", availablePlayers);
});

$("#add").click(function() {
    alert($("#playerGUID").val() + " - " + $("#player").val());
});

});

1 个答案:

答案 0 :(得分:0)

您的问题出在源函数中。 源函数使用请求传递术语参数进行查询,而您忽略它。 如果您使用availablePlayers进行查询,则应使用

source: availablePlayers

和当前函数在响应参数中映射{label,text}对象。

response: function (event, ui) {
        ui.content = $.map(ui.content, function(value, key) {
            return {
                label: value.name,
                value: value.guid
            }
        });
    }