AutoComplete Searching With Javascript
Tags: javascript
Published: 2018-01-18 20:38:03

---
title: AutoComplete Searching With Javascript
published: true
description: AutoComplete Searching using only javascript ES6
tags: #javascript
---

Hey,

In this post we will talk about autosearching with using only javascript no frameworks, we will need to fetch the data from the server so we will use Laravel for this.

Our example is we want to search for _contacts_.

so we need to create a _Contact_ Model `php artisan make:model Contact -m `

then go to <span style="text-decoration: underline;">_database/factories/ModelFactory.php_</span>

    $factory->define(App\Contact::class, function (Faker\Generator $faker)
    {
        return [
            'name'    => $faker->name,
            'email'   => $faker->unique()->safeEmail,
            'company' => $faker->sentence,
            'state'   => $faker->state,
        ];
    });

after we create our migration table and we migrate using this command `php artisan migrate`

we can now create our fake data in our console with `php artisan tinker`

then we create 50 fake contacts using this command `factory(App\Contact::class,50)->create();`

we create a link for this data

_<span style="text-decoration: underline;">routes/web.php</span>_

    Route::get('/contacts', function ()
    {
        return App\Contact::all();
    });

now we create our view

<span style="text-decoration: underline;">_autosearching.blade.php_</span>

    <html>
    <head>
        <title>AutoSearch</title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/css/bootstrap.min.css"
              integrity="sha384-Zug+QiDoJOrZ5t4lssLdxGhVrurbmBWopoEl+M6BdEfwnCJZtKxi1KgxUyJq13dy" crossorigin="anonymous">
    </head>
    <body class="bg-light">
    <div class="container" style="margin-top : 10%">
        <div class="row justify-content-center">
            <div class="col-4">
                <div class="bg-white">
                    <div class="input-group mb-3">
                        <input type="text" placeholder="Searching ..." class="form-control input-search">
                    </div>
                    <div class="search">

                    </div>
                </div>
            </div>
        </div>
    </div>
    </body>
    </html>

    const input = document.querySelector('.input-search');

    input.addEventListener('click',EnableArray);
    input.addEventListener('keyup',EnableArray);

![searching](https://image.ibb.co/jLk6bb/Screen_Shot_2018_01_03_at_8_20_35_PM.png "searching")

First of all with our javascript code we need to extract data from the contacts link

we use the new `fetch` method that return `promise` like `axios` if you ever use it. you can learn more about fetch [here](https://developer.mozilla.org/en-US/docs/Web/API/Fetch_API/Using_Fetch "fetch")

    const api = '/contacts';
    const contacts = [];

    fetch(api)
       .then(response => response.json())
       .then(blob => contacts.push(...blob));

then we need a method that can filter the contacts and get the one that resembles of the value we tape

we work with regex for the `'gi'` <span style="text-decoration: underline;">-g</span> is for global and <span style="text-decoration: underline;">-i</span> like upercase and lowercase are the same.

the value that we search is the name and the email

    function Searching(word) {
            return contacts.filter(contact => {
                const regex = new RegExp(word,'gi')
                return contact.name.match(regex) || contact.email.match(regex);
            });
        }

Now we add some events to our input we need the click event and also the keyup change event.

    const input = document.querySelector('.input-search');
    input.addEventListener('click',EnableArray);
    input.addEventListener('keyup',EnableArray);

Finally the `EnableArray` that will inner the html on our empty div

    function EnableArray() {
            const matches = Searching(this.value);
            const html = matches.map(match => {
                return ` <p class="p-2 d-flex flex-column border-bottom">
                            <span><small>${match.name}</small><small class="float-right">From ${match.state}</small></span>
                            <span><small>${match.email}</small></span>
                            <span><small>${match.company}</small></span>
                            </p>
                            <hr>
                        `;
            }).join('');
            search.innerHTML = html;
        }

<span style="text-decoration: underline;">![search](https://image.ibb.co/gC6Jpw/Screen_Shot_2018_01_03_at_8_30_58_PM.png "search")</span>

<span style="text-decoration: underline;">autosearching.blade.php</span>

If you dont want to follow all the steps there is the the full html file you can copy it directly

    <html>
    <head>
        <title>AutoSearch</title>
        <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0-beta.3/css/bootstrap.min.css"
              integrity="sha384-Zug+QiDoJOrZ5t4lssLdxGhVrurbmBWopoEl+M6BdEfwnCJZtKxi1KgxUyJq13dy" crossorigin="anonymous">
    </head>
    <body class="bg-light">
    <div class="container" style="margin-top : 10%">
        <div class="row justify-content-center">
            <div class="col-4">
                <div class="bg-white">
                    <div class="input-group mb-3">
                        <input type="text" placeholder="Searching ..." class="form-control input-search">
                    </div>
                    <div class="search">

                    </div>
                </div>
            </div>
        </div>
    </div>
    <script>
        const api = '/contacts';
        const input = document.querySelector('.input-search');
        const search = document.querySelector('.search');
        const container = document.querySelector('.container');
        const contacts = [];

        fetch(api)
            .then(response => response.json())
            .then(blob => contacts.push(...blob));

        function Searching(word) {
            return contacts.filter(contact => {
                const regex = new RegExp(word,'gi')
                return contact.name.match(regex) || contact.email.match(regex);
            });
        }

        function EnableArray() {
            const matches = Searching(this.value);
            const html = matches.map(match => {
                return ` <p class="p-2 d-flex flex-column border-bottom">
                            <span><small>${match.name}</small><small class="float-right">From ${match.state}</small></span>
                            <span><small>${match.email}</small></span>
                            <span><small>${match.company}</small></span>
                            </p>
                            <hr>
                        `;
            }).join('');
            search.innerHTML = html;
        }

        input.addEventListener('click',EnableArray);
        input.addEventListener('keyup',EnableArray);

        container.addEventListener('click',function() {
            search.innerHTML = ''
        });
    </script>
    </body>
    </html>