I have read multiple articles on here concerning arrays, .each, and other solutions, but none of these have showed me the issue in what I am trying to do.
I want to make it to where a button is clicked, the value of that button is stored, and then compared to values of objects in an array. If a match is found I want that match to be .append into a portion of the page.
I know the button click is registering. I have .append that into the page and been displayed the proper value. I know I can iterate all of the objects in the array with .each and .append them to the page as I have done that as well. However if I just .append employee from the example below I get [object Object] and thus I know my comparison operator is not functioning correctly. Any help if showing me my problem or explaining why it is not working is greatly appreciated.
Here is the button:
<button type="button" id="german" class="searchButton" value="German">German</button>
This is what one line my array looks like
employees = [
{ "firstName":"Alex", "lastName":"Hagerman", "language":"German", "department":"Nuerology", "position":"Nurse", "skill":"Infection" },
]
There are more lines but this works for the example.
This is the function I want to compare the button value to the array value. (if I was to just .append employee here I get [object Object])
$(document).ready(function(){
$('button').click(function(){
var buttonValue = $(this).val();
$.each(employees, function (i, employee) {
if (employee == buttonValue) {
$('#resultsView').append('<div class="searchResults">'+employee.firstName+employee.lastName+'<br />'+employee.language+'<br />'+employee.department+employee.position+'<br />'+employee.skill+'</div>');
}
else {
$('#resultsView').append('<div id="resultsView" class="noResult">No results found</div>');
}
});
});
});
Currently I only get No Results Found.
You’ve got a few problems – the first is that you’re trying to compare the raw object to the button value:
(employee == buttonValue). Instead you need to compare to whatever you’re looking for, ie for languageemployee.language == buttonValueThe second is that if any object in the array doesn’t match it’ll append
no results. This can be resolved by having a flag to indicate if a result was found or not – outside of the.eachloop make the flag and set to false – if a result is found set flag to true. After the.eachloop check to see if a result was set – if not, display no result.Here’s a working solution.