Pull data to an input when typing in the field

3

I need a script that, when I type a word inside a field, it pulls all the data that is related to that word, like an example Facebook, in the search bar, when we will type something it already comes bringing everything that is related to it, could anyone help me?

Or, here in Stack Overflow's own site we have to insert a tag, it shows everything that has related the letters that were typed in the field!

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

    
asked by anonymous 03.03.2017 / 20:42

2 answers

2

What you are looking for is called Typeahead .

Normally the solution does not come by itself: it comes with another framework , such as Bootstrap. There are some implementations of Typeahead for Bootstrap:

Or just using jQuery:

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

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

I do not 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 say you're bringing people's names and their Id's ( same as the first example here < a>, but 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 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);
    }
    
03.03.2017 / 20:48
0

In this case, it does not pull the database by typing, but it pulls all the data and assembles the script needed for autocomplete, that is, it provides suggestions as you type in the field.

I used php because I only know php and asp to access the database.

<?php
$con = mysqli_connect("localhost", "USUARRIO", "SENHA", "DB");
$query = ("SELECT COLUNA FROM TABELA");
$result = mysqli_query($con,$query);

if (mysqli_num_rows($result) > 0) {
  while($row = mysqli_fetch_assoc($result)) {
   $dados = $dados."\"".$row["pedido"]."\",";
  }
}
$dados = substr($dados,0,-1); //retira a ultima virgula
mysqli_close($con);
?>

<!doctype html>
<html>
<head>
<link rel="stylesheet" href="http://code.jquery.com/ui/1.12.1/themes/base/jquery-ui.css">
<link rel="stylesheet" href="https://jqueryui.com/resources/demos/style.css">
<script src="https://code.jquery.com/jquery-1.12.4.js"></script><scriptsrc="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<script>
$( function() {
  var availableTags = [<?php echo $dados?>];
  $( "#tags" ).autocomplete({
    source: availableTags
  });
} );
</script>
</head>
<body>
<div class="ui-widget">
<label for="tags">Tags: </label>
<input id="tags">
</div>
</body>
</html>



    
04.03.2017 / 02:44