I have the following JSON and Jquery Code:
JSON
{
"employees":[
{
"name": "Sandy"
},
{
"name": "Megan"
},
{
"name": "Pat"
},
{
"name": "Susan"
}
]
}
JQuery
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=iso-8859-1" />
<script type="text/javascript" src="js/jquery-1.6.4.js"></script>
<script type="text/javascript">
$(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("<li>" + empName + "</li>");
}
}
});
}
})
})
</script>
</head>
<body>
<input type="text" width="25" id="myInput">
<ul id="myList"></ul>
</body>
</html>
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.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
==comparisionUpdated DEMO
Change your for loop as below,
DEMO