match filter

by Sparrow Squire

HTML

<input id="matchFilter" type="text">
<ul id="displayResults"></ul>

CSS

body {
  background: #222;
  text-align: center
}

input, ul {
  color: #F38630;
  background: #111;
  border: 1px solid #000;
  padding: 5px;
  margin-bottom 15px
}

li {list-style: none}

#displayResults {
  display: none;
  max-height: 200px;
  overflow: auto;
}

JavaScript

var arr = [
	"Aardvark",
	"ant",
  "anteater",
  "bat",
  "Bee",
  "Butterfly",
  "cat",
  "dog",
  "dolphin",
  "eel",
  "elephant",
  "fox",
  "foal",
  "goat",
  "horse",
  "iguana",
  "panther",
  "seal",
  "tiger"  
];

var matches = [];

$('#matchFilter').keyup(function(e) {
	$('#displayResults').show();
  var _this = $(this).val().toLowerCase();//Set to lowercase for case-insensitive
  filterByMatch(_this);
  
  if(e.which == 13) {
  	$('#displayResults').hide();
  }
});

$('#matchFilter').focus(function() {
    var _this = $(this).val().toLowerCase(); //TODO: remove dupe //Set to lowercase for case-insensitive
    filterByMatch(_this); //TODO: remove dupe
    $('#displayResults').show();
});

$('#matchFilter').blur(function() {
    $('#displayResults').hide();
});

function filterByMatch(searchPhrase) {  
		matches = [];

		$.each(arr, function(i, str) {
        //if searchPhrase empty display all OR if theres a searchPhrase that contains any matches display matching
			  if ((searchPhrase == "") || (searchPhrase != "" && str.toLowerCase().indexOf(searchPhrase) >= 0)) {
      		  matches.push('<li>' + str + '</li>');
        }
	  });
      
    //if matches: display
    if (matches.length > 0) {
        $('#displayResults').html(matches);
    //else no matches: 
    } else {
        $('#displayResults').html('<li>No Results</li>');
    }
}