I have the following JSON and Jquery Code:
JSON
{
"employees":[
{
"name": "Sandy"
},
{
"name": "Megan"
},
{
"name": "Pat"
},
{
"name": "Susan"
}
]
}
JQuery
$(document).ready(function(){
jQuery.ajax({
type: "GET",
url: "myJson.json",
dataType: "json",
async: "true",
contentType: "application/x-javascript; charset=utf-8",
cache: "false",
success: function(response){
$("input#myInput").live("keyup", function(e){
var val = $("input#myInput").val();
var len = $("input#myInput").val().length;
for (var x = 0; x < response.employees.length; x++) {
var empName = response.employees[x].name;
var valChar = val.substring(0, len);
var nameChar = empName.substring(0, len);
if (nameChar.search(valChar) != -1) {
$("ul#myList").append("
" + empName + "");
}
}
});
}
})
})
What I want to do
When I type a character in the input field such as M/P/S, it should loop through the JSON file and return matching results. So,
M will return Megan
S will return Sandy and Susan
P will return Pat
Problem
Currently, my code is working. BUT only when I input the characters in upper case. If I type in m/p/s, it does not return anything.
How can I make this case-insensitive so that it works for both
M/P/S
m/p/s
解決方案
Edit: Some improvements in your code
val and val.substring(0,len) is same so you don't need to do do substring as len is calculated from val.
You don't need to do search as you use substring and get the exact length of val.. so you can do a simple == comparision
for (var x = 0; x < resp.employees.length; x++) {
var empName = resp.employees[x].name;
var valChar = val.toLowerCase();
var nameChar = empName.substring(0, len).toLowerCase();
if (nameChar === valChar) {
$("ul#myList").append("
" + empName + "");
}
}
Updated DEMO
Change your for loop as below,
for (var x = 0; x < resp.employees.length; x++) {
var empName = resp.employees[x].name;
var valChar = val.substring(0, len).toLowerCase();
var nameChar = empName.substring(0, len).toLowerCase();
if (nameChar.search(valChar) != -1) {
$("ul#myList").append("
" + empName + "");
}
}