简体   繁体   中英

Loop through an array of names and check if value of keypress matches a character in a name

I got a search input that uses an angular filter, it works fine but there's one thing that I need to fix but haven't been able to. If the user doesn't enter a character that actually exists in any of the names in the scope.names array, then I don't want the div containing the search hits to be shown at all. This if statement: if (keyValue != scope.names[i].charAt(j)) ALWAYS evaluates to true for some reason, so even when a match IS found, the div isn't shown. I have checked if the loop works as intended and it does, so the problem doesn't lie there. What am I doing wrong?

This is where the names are being stored:

app.controller('addressBookController', function ($scope) {

    $scope.names = [];
});

And here's the code handling the hiding/showing:

var input = document.getElementById('search');
    input.addEventListener('keyup', function(e) {

        var scope = angular.element(document.getElementById('address-book')).scope();
        var searchHits = document.getElementById('search-hits');
        var keyValue = String.fromCharCode(e.keyCode);
            keyValue = keyValue.toLowerCase() + keyValue.slice(1);    

            if (input.value.length >= 0) {
                searchHits.style.display = 'block';
            }

            if (input.value.length === 0) {
                searchHits.style.display = 'none';    
            }

            for (i = 0; i < scope.names.length; i++) {

                for (j = 0; j < scope.names[i].length; j++) {

                    if (keyValue != scope.names[i].charAt(j)) {
                        searchHits.style.display = 'none';    
                    }
                }
            }

The problem is with below logic of hiding the div in case of missed hit.

if (keyValue != scope.names[i].charAt(j)) {
     searchHits.style.display = 'none';    
 }

lets say user input 'a' and your array contains one name as 'ba', so when loop starts obviously 'a' != 'b' would be true and thus hiding your div which is not unhided again.
Instead of doing this you can modify your logic as below (there are other better way using angular ngShow):

for (var i = 0; i < scope.names.length; i++) {
    if (scope.names[i].indexOf(keyValue) === -1) {
        searchHits.style.display = 'none';
    }
}

The above logic is as per your requirement and will hide the searchHits div in case keyValue not present in all of the names.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM