blogpost: how to build a live search with JSON

How to build a live search with JSON

Posted on:

This is a prototype of a project done on a client website. For the Search page, the client wanted to have a live search box wherein as the user types the name of the member in the input box, results show up at the bottom. The results show the picture of the member and also a short bio.

We decided to have the member information including the image and the short bio stored in a JSON file on the server.

What is a JSON file?

JSON stands for Javascript Object Notation. It is a text file used to exchange data between browser and server. The data is stored as javascript objects.

Example of a JSON file

"name":"Barot Bellingham",
"reknown":"Royal Academy of Painting and Sculpture",
"bio":"Barot has just finished his final year at The Royal Academy of Painting and Sculpture, where he excelled in glass etching paintings and portraiture. Hailed as one of the most diverse artists of his generation, Barot is equally as skilled with watercolors as he is with oils, and is just as well-balanced in different subject areas. Barot's collection entitled \"The Un-Collection\" will adorn the walls of Gilbert Hall, depicting his range of skills and sensibilities - all of them, uniquely Barot, yet undeniably different"
  • The search results were stored in a JSON file.
  • Setup the HTML for the search box.
  • The input box ‘keyup’ event triggered the search process.
  • The results are rendered on the page below the search box.

The html code on the page

<div id="searchArea">
<label for="search">Live Search </label>
Enter name/info to start the search
<input type="search" placeholder="enter name/info" name="search" id="search">
<div id="update"></div>

Javascript code snippet

var searchField = $('#search').val();
var myExp = new RegExp(searchField, "i");
$.getJSON('data.json', function(data){
var output ='<ul class="searchresults">';
$.each(data, function(key, val){
if(( != -1) || ( != -1)) {
output += '<li>';
output += '<h2>' + + '</h2>';
output += '<img src="images/' + val.shortname + '_tn.jpg" alt="' + + '">' ;
output += '' + + '';
output += '</li>';
output += '</ul>';

I hope you found this article useful and interesting.