Le Yang
Le Yang

Reputation: 88

How to implement search box function for static website in code?

I have almost finished my own website, and I am wondering how simple I can implement search function in current page. It's static and only need to show list items which include users' input. Some answers from stackoverflow advise Google API, but it will show Google logo in the search box, that's not work for me.

Is there any 3rd party API or some simple code can satisfy my requirement?

Upvotes: 1

Views: 4181

Answers (1)

Out of Rain
Out of Rain

Reputation: 170

It's not easy to create your own search library, and also you don't need Google Search API if you only require search function in static website. You can consider to use Angular JS to excute.

1.1 Defined ng-app & ng-controller to main body function

<body ng-app="instantSearch" ng-controller="InstantSearchController">

1.2 Add ng-model to search box function

<input ng-model="searchString">

1.3 Add ng-repeat to div or li function to show the data based on search from input box

<div ng--repeat="i in items | searchFor: searchString">

2.1 Define a new module for your app

var app = angular.module("instantSearch", []);

2.2 Create the instant search filter

app.filter('searchFor', function() { 
    return function(arr, searchString) { 
        if(!searchString){ 
            return arr; 
        } 
        var result = []; 
        searchString = searchString.toLowerCase(); 
        angular.forEach(arr, function(item) { 
            if(item.title.toLowerCase().indexOf(searchString) !== -1){ 
                result.push(item); 
            } 
        }); 
        return result; 
    }; 
});

2.3 Edit your controller

function InstantSearchController($scope) {
    $scope.items = [
        {
            title1:'abc',
            title2:'def'
        },
        {
            title1:'ghi',
            title2:'jkl'
        }
    ];
}

And now you can display the items which has the same result in your search box.

Upvotes: 2

Related Questions