DEV Community

mohamed benhida
mohamed benhida

Posted on

AutoComplete Searching With 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 database/factories/ModelFactory.php

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

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

routes/web.php

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

now we create our view

autosearching.blade.php

<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);
Enter fullscreen mode Exit fullscreen mode

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

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

fetch(api)
   .then(response => response.json())
   .then(blob => contacts.push(...blob));
Enter fullscreen mode Exit fullscreen mode

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' -g is for global and -i 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);
        });
    }
Enter fullscreen mode Exit fullscreen mode

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);
Enter fullscreen mode Exit fullscreen mode

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;
    }
Enter fullscreen mode Exit fullscreen mode

search

autosearching.blade.php

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>
Enter fullscreen mode Exit fullscreen mode

Top comments (0)