0

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

Vishnu Prasad
  • 729
  • 1
  • 11
  • 28

2 Answers2

1

Use RegExp to create new regular expression

var matchMe = new RegExp('^' + country, 'i'); character ^ will search only at begining, option 'i' is "case insensitive", so no need to lowercase them before comparision

there is also "g" option for global search and "m" for multiline search

learn more about regular expressions http://www.w3schools.com/js/js_regexp.asp

then use it in condition

if (countries[i].name.search(matchMe) > -1 )

modified code - line 37 and 40 http://jsfiddle.net/f5g0nr8h/

  • Sometimes the result show "undefined" as the search result(In Internet Explorer only). Is there any remedy for that?? – Vishnu Prasad Jun 16 '15 at 09:22
  • which version of IE? btw, sometimes, you need to escape that regexp string to prevent errors (for example you can brake it with \ char or similar typing in text input), use this http://stackoverflow.com/questions/3561493/is-there-a-regexp-escape-function-in-javascript – Tamaro Tamaroidny Jun 16 '15 at 17:30
1

You are adding matches to the results via string.indexOf(), the return value is 0 if the string starts with the search pattern. Therefore you could use:

if ( (countriesMatch.indexOf(country.toLowerCase()) === 0) ) {
    matches.push( {'id': i, 'name': countries[i].name} );
}
jandob
  • 651
  • 5
  • 14