Reputation: 110
I've been working on this simple script for a few hours now and have hit a wall. I have an Array comprised of JSON values. When a user searches for a string and clicks the button, the script checks the string against the values stored in the Array.
The section I'm stuck on is the conditional, which always returns no match - even if I enter a string which I know is in the JSON file.
Code below. Any guidance/pointers would be greatly appreciated.
Thanks for your help!
Mark.
$('#validate-info').on('click', function(){
// Get data, initiate callback
$.getJSON('memberships.json', validateMembership);
// Execute callback function
function validateMembership(data) {
// Capture entered value
var userVal = document.getElementById('form-data').value;
console.log(userVal);
var infoTxt = '';
// Push all items into an Array
var infoArray = [];
$.each(data, function(member, memberInfo) {
infoTxt += '<p><strong>Name:</strong> ' + memberInfo.name + '<br />';
infoTxt += '<strong>Membership No.:</strong> ' + memberInfo.number + '<br />';
infoTxt += '<strong>Expiry Date:</strong> ' + memberInfo.expiry + '</p>';
infoArray.push({
name: memberInfo.name,
number: memberInfo.number,
expiry: memberInfo.expiry
});
});
if ($.inArray(userVal, infoArray) > -1 ) {
// the value is in the array
$('#response').html('<p style="color: green;">In the array</p>');
} else {
$('#response').html('<p style="color: red;">Sorry, no matches.</p>');
}
}
});
Upvotes: 0
Views: 89
Reputation: 781096
You're comparing the input string against the objects, and they'll never match. You need to compare just with the name. You can use the Array.prototype.some
function to test if any of them match.
if (infoArray.some(function(obj) {
return obj.name == userVal;
})) {
$('#response').html('<p style="color: green;">In the array</p>');
} else {
$('#response').html('<p style="color: red;">Sorry, no matches.</p>');
}
You could also do it during the loop that pushes into infoArray
.
var match = false;
$.each(data, function(member, memberInfo) {
infoTxt += '<p><strong>Name:</strong> ' + memberInfo.name + '<br />';
infoTxt += '<strong>Membership No.:</strong> ' + memberInfo.number + '<br />';
infoTxt += '<strong>Expiry Date:</strong> ' + memberInfo.expiry + '</p>';
infoArray.push({
name: memberInfo.name,
number: memberInfo.number,
expiry: memberInfo.expiry
});
if (memberInfo.name == userVal) {
match = true;
}
});
if (match) {
$('#response').html('<p style="color: green;">In the array</p>');
} else {
$('#response').html('<p style="color: red;">Sorry, no matches.</p>');
}
Upvotes: 2