I have created a country search when typing in the input box.
HTML is
Country<div class="holder_form"><input id="country" name="country" type="text" placeholder="Country" value="">
<ul id="country_wrapper"></ul>
Javascript is
var countries={
"1": {
"name": "Afghanistan"
},
"2": {
"name": "India"
},
"3": {
"name": "Canada"
},
"4": {
"name": "Estonia"
},
"5": {
"name": "Greece"
},
"6": {
"name": "Kenya"
},
"7": {
"name": "Liberia"
},
"8": {
"name": "Nepal"
}
}
$("#country").keyup(function (e) {
var country = $( "#country" ).val();
var len = country.length;
if(len <=0 && country!=''){
return false;
}
else if(len > 0){
var matches = [];
for (var i in countries) {
var countriesMatch = countries[i].name.toLowerCase();
if ( (countriesMatch.indexOf(country.toLowerCase()) != -1) ) {
matches.push( {'id': i, 'name': countries[i].name} );
}
}
var content='';
if ( matches.length == 0 ) {
$('#country_wrapper').css('margin-top','20');
content = '<li style="font-weight:bold;font-size: 18px;"><div class="nomatchfound">No match found</div></li>';
$('#country_wrapper').html(content).show();
return;
}
for (var i in matches) {
content += '<li style="font-weight:bold;font-size: 18px;"><a data-id="' + matches[i].id + '" class="country-select-item"><div id='+matches[i].name+' class="matchfound">'+matches[i].name+'</div></a></li>';
}
$('#country_wrapper').html(content).show();
$('.matchfound').click(function(e) {
var countryName = $(this).text();
$( "#country" ).val(countryName);
$('#country_wrapper').html('')
$('#country_wrapper').css('display','none');
});
}
});
Here is the Jsfiddle demo
It works fine... :)
But I need to show only the country name which start with the letter(alphabet) I pressed in input box
ie,
Here when I pressed key "a" it shows all country names contining letter "a". But I need to get only country names starting with "a" in the list.. How is it possible? Thanks in advance