The autocomplete search box suggest data options to the user based on its input.
From there, it can select the option.
In the demonstration, I am creating a search box and display suggestion list whenever the user input value in the search box. If a user clicks outside the suggestion list then hide it.
Set a selected value to search box when an option gets selected.
I am using PHP with AngularJS to fetch records.
Create a textbox element and for display, suggestion created the
Search value on
Completed Code
Define
You can check my earlier tutorial to learn the implementation of this functionality with jQuery.
In the demonstration, I am creating a search box and display suggestion list whenever the user input value in the search box. If a user clicks outside the suggestion list then hide it.
Set a selected value to search box when an option gets selected.
I am using PHP with AngularJS to fetch records.
1. Table structure
I am usingusers
table in the tutorial example.CREATE TABLE `users` ( `id` int(11) NOT NULL PRIMARY KEY AUTO_INCREMENT, `username` varchar(80) NOT NULL, `name` varchar(80) NOT NULL, `email` varchar(80) NOT NULL ) ENGINE=InnoDB DEFAULT CHARSET=latin1;
2. Configuration
Create a newconfig.php
file.
Completed Code
<?php $host = "localhost"; /* Host name */ $user = "root"; /* User */ $password = ""; /* Password */ $dbname = "tutorial"; /* Database name */ $con = mysqli_connect($host, $user, $password,$dbname); // Check connection if (!$con) { die("Connection failed: " . mysqli_connect_error()); }
3. HTML
Addng-click='containerClicked()'
on <div class='container'>
to detect outside click of a search box and suggestion list <ul><li>
.Create a textbox element and for display, suggestion created the
<ul> <li>
.- On textbox defined
ng-keyup='fetchUsers()
‘ andng-model
directive.Also, addng-click='searchboxClicked($event)'
. - Show list of suggestion result on
<li>
usingng-repeat
directive. Defineng-click
directive which callssetValue($index,$event)
.
<body ng-app='myapp'> <div class='container' ng-controller="fetchCtrl" ng-click='containerClicked();' > <input type='text' ng-keyup='fetchUsers()' ng-click='searchboxClicked($event);' ng-model='searchText' placeholder='Enter text'><br> <ul id='searchResult' > <li ng-click='setValue($index,$event)' ng-repeat="result in searchResult" > {{ result.name }} </li> </ul> </div> </body>
4. CSS
.container{ width: 100%; height: 300px; } #searchResult{ list-style: none; padding: 0px; width: 250px; position: absolute; margin: 0; } #searchResult li{ background: lavender; padding: 4px; margin-bottom: 1px; } #searchResult li:nth-child(even){ background: cadetblue; color: white; } #searchResult li:hover{ cursor: pointer; } input[type=text]{ padding: 5px; width: 250px; letter-spacing: 1px; }
5. PHP
Create a newgetData.php
file.Search value on
users
table according to POST value and limit query result to 5. Initialize the array with the users name and return a JSON value.Completed Code
<?php include 'config.php'; $data = json_decode(file_get_contents("php://input")); $search = $data->searchText; // Fetch 5 records $sel = mysqli_query($con,"select * from users where name like '%".$search."%' limit 5"); $data = array(); while ($row = mysqli_fetch_array($sel)) { $data[] = array("name"=>$row['name']); } echo json_encode($data);
6. Script
Defined 4 methods in the controller –- fetchUsers() – This function is been called when
keydown
event trigger on the input box.
From here, check the input search text length if it is 0 then empty the $scope.searchResult otherwise send
$http
request where pass input value $scope.searchText
as data
. Initialize $scope.searchResult
with response.data
on successfully callback.- setValue() – This function is called when an option gets selected from suggestion list. Initialize
$scope.searchText
with$scope.searchResult[index].name
(selected value) and empty$scope.searchResult
. Execute$event.stopPropagation()
to stop parent click from trigger. - searchboxClicked() – Call on search box click. From here, execute
$event.stopPropagation()
to stop parent click from trigger. - containerClicked() – Call on
<div class='container'>
click. Empty the$scope.searchResult
.
var fetch = angular.module('myapp', []); fetch.controller('fetchCtrl', ['$scope', '$http', function ($scope, $http) { // Fetch data $scope.fetchUsers = function(){ var searchText_len = $scope.searchText.trim().length; // Check search text length if(searchText_len > 0){ $http({ method: 'post', url: 'getData.php', data: {searchText:$scope.searchText} }).then(function successCallback(response) { $scope.searchResult = response.data; }); }else{ $scope.searchResult = {}; } } // Set value to search box $scope.setValue = function(index,$event){ $scope.searchText = $scope.searchResult[index].name; $scope.searchResult = {}; $event.stopPropagation(); } $scope.searchboxClicked = function($event){ $event.stopPropagation(); } $scope.containerClicked = function(){ $scope.searchResult = {}; } }]);
7. Conclusion
The autocomplete search allows the user to search on the list and select a value from the suggestions.Define
ng-click
on the parent to detect outside of suggestion list and search box. Stop the parent click from trigger using .stopPropagation()
when clicked on the suggestion list or search box.You can check my earlier tutorial to learn the implementation of this functionality with jQuery.
0 Comments:
Post a Comment