Displaying array value based on a certain array key as a user type in a text field
我已经研究了用户输入的显示部分数组值匹配,并尝试获得相同的结果。
不同之处在于数组格式。我希望搜索文本值与数组键name匹配。
无论我在文本字段中键入什么,它都会显示"未找到匹配项!"我永远也无法显示这些名字。似乎无法识别播放机[X].name.indexof()。如何显示名称?
这是小提琴
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 | var players = [ {"id" :"23012", "name" :"Scott", "first" :"Stve", "last" :"Scott" }, {"id" :"22904", "name" :"Phillips, A", "first" :"Adam", "last" :"Phillips"}, {"id" :"45783", "name" :"Phillips, T", "first" :"Tom", "last" :"Phillips" }, {"id" :"54762", "name" :"Scobery", "first" :"Don", "last" :"Scobery" }, {"id" :"78903", "name" :"Phillip", "first" :"Roger", "last" :"Phillip"} ] $("#searchField").on("keyup", function() { $(".append").empty(); if($("#searchField").val() !=""){ for(var x = 0; x < players.length; x++){ if(players[x].name.indexOf(($("#searchField").val()).toLowerCase()) == 0){ $(".append").append(players[x].name+""); } else { $(".append").html("no match found!"); } } } }); |
更新小提琴
您将在第一次负搜索时覆盖所有搜索结果。因为追加追加结果,最初没有找到用.html()指令杀死所有追加的子项。只是那个错误。我不确定你用托洛维卡糖,但这是另一个故事。
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 | var players = [{ "id":"23012", "name":"Scott", "first":"Stve", "last":"Scott" }, { "id":"22904", "name":"Phillips, A", "first":"Adam", "last":"Phillips" }, { "id":"45783", "name":"Phillips, T", "first":"Tom", "last":"Phillips" }, { "id":"54762", "name":"Scobery", "first":"Don", "last":"Scobery" }, { "id":"78903", "name":"Phillip", "first":"Roger", "last":"Phillip" }] $("#searchField").on("keyup", function () { var found = false; $(".append").empty(); if ($("#searchField").val() !="") { for (var x = 0; x < players.length; x++) { if (players[x].name.indexOf($("#searchField").val()) >= 0) { found = true; $(".append").append(players[x].name +""); } } if (!found) { $(".append").html("no match found"); } } }); // searchField on |
要使搜索完全不区分大小写:
1 | if (players[x].name.toLowerCase().indexOf($("#searchField").val().toLowerCase()) == 0) |
号
垃圾邮件小写。(对对象和输入)