Giacomo Balli profile picture
Giacomo Balli
Your Technology Advisor

Over two decades of experience at your service.
I help small business owners make better decisions.

Let's Chat LinkedIn

Dynamic search suggest

This code sample will allow you to provide suggestions while the user is typing. Ideal for search fields.

HTML
<input type="text" placeholder="Begin typing a tag..." onkeyup="searchSuggest(this)" />

CSS
#suggestHolder {
    position: absolute;
    background-color: white;
    border-bottom-left-radius: 10px;
    border-bottom-right-radius: 10px;
    -webkit-transition: all .5s;
    overflow: hidden;
}

#suggestHolder li {
    border-left: 1px solid #ccc;
    border-bottom: 1px solid #ccc;
    border-right: 1px solid #ccc;
    padding: 10px 20px;
    overflow: hidden !important;
}
#suggestHolder li:first-child {
    border-top: none;
}

JavaScript
defaultSuggestTerms = ['john','jack','james','jason'];
function searchSuggest(el) {
	var txt=el.value;
    if (txt.length < 1) {
        suggestHolder.innerHTML = '';
        return;
    }
    if (event.which === 13) {
        suggestHolder.innerHTML = '';
        return;
    }
    txt = txt.toLowerCase();
    var searchSuggestions = '';
    var suggestCnt = 0;
    for (var p = 0; p < defaultSuggestTerms.length; p++) {
        if (defaultSuggestTerms[p].toLowerCase().match(txt)) {
            suggestCnt++;
            searchSuggestions += '<li onclick="">' + defaultSuggestTerms[p] + '</li>';
            if (suggestCnt > 5) {
                break;
            }
        }
    }
	if (typeof suggestHolder === "undefined"){
		suggestHolder=document.createElement("UL");
		suggestHolder.id="suggestHolder";
		document.body.appendChild(suggestHolder);
		suggestHolder.style.top=(el.offsetTop+el.offsetHeight)+"px";
		suggestHolder.style.left=el.offsetLeft+"px";
		suggestHolder.style.width=el.offsetWidth+"px";
	}
    suggestHolder.innerHTML = searchSuggestions;
}

Directions:
- add your list of possible suggestions to defaultSuggestTerms.
- by default number of suggestions is limited to 5 but feel free to change the value.

Note:
This snippet focuses on iOS development. Make sure to verify/adapt any vendor prefixes. Back to main listing.

Published: Mon, Jan 11 2016 @ 12:30:16
Back to Blog