Jon Snow's papa Jon Snow's papa - 5 months ago 17
Javascript Question

jQuery search input

I have got this HTML:

<input type="text" placeholder="Type country name" class="Cinp">
<div class="contres"></div>


And this jQuery code:

var country_list= ["Argentina","Armenia","Aruba","Australia","Austria","Azerbaijan"];
var results = [];
var selected= [];

$(".Cinp").keyup(function(e) {
var value=$(this).val();

if (e.which >= 65 && e.which <= 90 || e.which==8) {
if (value.length!=0) {
function filter(letter) {
var len = country_list.length;
var i = 0;

while(i < len) {
if (country_list[i].indexOf(letter) == 0 || country_list[i].indexOf(letter.toUpperCase()) == 0 ) {
results.push(country_list[i]);
$(".contres").append(country_list[i]);
}
i++;
}
}
}
}
}


So it works perfectly when I type only first letter, but when I type
Az
it should return
Azerbaijan
only but it returns all countries that start with
a
.

Answer
            $(".contres").clear(); /// whether need that?

             while(i < len) {
                 if (country_list[i].indexOf(letter) == 0 || country_list[i].indexOf(letter.toUpperCase()) == 0 ){
                    results.push(country_list[i]);
                    $(".contres").append(country_list[i]);
                    }
                    i++;
                }
            }