javascript – Pulling data from an input by typing in the field

Question:

I need a script that, when I'm typing a word into a field, it pulls all the data that are related to that word, such as Facebook, in the search bar, when we're going to type something it already brings everything that is related to that, could someone help me?

Or, here on the Stack Overflow website, there is the part where we insert a Tag, it shows everything related to the letters that were typed in the field!

Only in my case I wanted it to pull data from a table by itself.

Answer:

The one you are looking for is called Typeahead .

Usually the solution doesn't come alone: ​​it comes with another framework such as Bootstrap. There are some Typeahead implementations for Bootstrap:

Or using just jQuery:

Depending on the implementation you choose, there may be a different Ajax format, usually asking for JSON. For these cases, implement an Action in Controller that returns JSON:

public JsonResult ActionQueTrabalhaComTypeAhead()
{
    var exemplo = new String[] { "1", "2", "3" };
    return Json(exemplo, JsonRequestBehavior.AllowGet); 
}

I don't know what you're using to bring information from the database, but I'll assume it's the Entity Framework.

In this case, let's suppose that you are bringing people's names and their respective Id's (like the first example here , only with people instead of states). First let's set up the presentation. It should contain something like this:

<div id="exemplo">
  <input class="typeahead" type="text" id="typeaheadpessoas" placeholder="Nomes de Pessoas">
</div>

Typeahead works with a prediction engine called Bloodhound. It can be configured like this:

        window.pessoas = new Bloodhound({
            identify: function (obj) { return obj.Descricao; },
            datumTokenizer: function (d) {
                return Bloodhound.tokenizers.whitespace(d.Descricao);
            },
            queryTokenizer: Bloodhound.tokenizers.whitespace,
            prefetch: {
                ttl: 0,
                url: '@Url.Action("PreCargaTypeAhead", "Pessoas")'
            },
            remote: {
                url: '@Url.Action("ActionQueTrabalhaComTypeAhead", "Pessoas")',
                replace: function (url, uriEncodedQuery) {
                    return url + '?termo=' + uriEncodedQuery;
                }
            }
        });

        window.pessoas.initialize();
        window.typeahead_pessoas_data = {
            name: 'pessoas',
            displayKey: 'Descricao',
            source: window.pessoas,
            limit: 10,
            templates: {
                empty: [
                  '<div class="typeahead-empty-message">',
                    'Não encontrado',
                  '</div>'
                ].join('\n')
            }
        };

        window.typeahead_options = {
            hint: true,
            highlight: true,
            minLength: 3
        };

        $('#typeaheadpessoas').typeahead(window.typeahead_options, typeahead_pessoas_data
        ).on('typeahead:selected', function (event, data) {
            // Faça alguma coisa aqui com data. Data é um json.
        });

An example of data search:

    [HttpGet]
    public async Task<JsonResult> ActionQueTrabalhaComTypeAhead(String termo)
    {
        if (String.IsNullOrEmpty(termo)) return Json(null, JsonRequestBehavior.AllowGet);

        // Aqui faço a pesquisa ao banco de dados.
        // Pesquiso ou pelo nome da pessoa ou pelo seu CPF.
        var pessoas = await db.Pessoas.Where(r => r.Nome.Contains(termo) || r.Cpf.Contains(termo)).ToListAsync();

        return Json(pessoas.Select(p => new
        {
            PessoaId = p.PessoaId,
            Descricao = p.Nome + " - " + p.Cpf
        }), JsonRequestBehavior.AllowGet);
    }
Scroll to Top