Reputation: 23
On keyup of an input I'm trying to do a live search from my database. But whenever I type somemthing I get an error saying
Uncaught TypeError: value.voedselID.search is not a function.
How can I fix this? Here is how my json looks like
[{
"voedselID": 1,
"voedselNaam": "Apple",
"gram": 100,
"carb": 11,
"eiwitten": 1,
"vet": 0,
"calorieen": 49
},
{
"voedselID": 2,
"voedselNaam": "Kip",
"gram": 100,
"carb": 0,
"eiwitten": 12,
"vet": 3,
"calorieen": 76
}
]
And here is how my code looks like
$(document).on('keyup', '.inputUpdateFood', function(e) {
var searchField = $('#inputUpdateFood').val();
var expression = new RegExp(searchField, "i");
var output = '';
$.getJSON('http://localhost:8080/Voedsel/getAll', function(data) {
$.each(data, function(key, value) {
if (value['voedselID'].search(expression) != -1 || value.voedselNaam.search(expression) != -1) {
output += '<input type="radio" name="foodSug" value="' + val.voedselNaam + '">' + val.voedselNaam + '<br>'
$('.suggestion').append(output);
}
})
})
});
Upvotes: 1
Views: 2138
Reputation: 177965
It is more understandable to use a regex match or test() but since your ID is numeric it needs to be a string to be used with a regex
Your each is a loop on an array, not a key/value object
So
var data = [{
"voedselID": 1,
"voedselNaam": "Apple",
"gram": 100,
"carb": 11,
"eiwitten": 1,
"vet": 0,
"calorieen": 49
},
{
"voedselID": 2,
"voedselNaam": "Kip",
"gram": 100,
"carb": 0,
"eiwitten": 12,
"vet": 3,
"calorieen": 76
}
]
var searchField = "kip";
var re = new RegExp(searchField,"i"), output="";
$.each(data, function(_,item) {
console.log(item,item.voedselNaam.match(re))
if (String(item.voedselID).match(re) || item.voedselNaam.match(re) ) {
output += '<input type="radio" name="foodSug" value="' + item.voedselNaam + '">' + item.voedselNaam + '<br>'
$('.suggestion').append(output);
}
})
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="suggestion"></div>
Upvotes: 1
Reputation: 424
The search function seems to be a method of the String class.
So, you should convert the value to String.
Have you tried to use one of the following code in your condition ?
String(value['voedselID']).search(expression) != -1
value['voedselID'].toString().search(expression) != -1
https://www.w3schools.com/jsref/jsref_search.asp
Upvotes: 0