Pull data from an input when typing in the field

Asked

Viewed 2,772 times

3

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

Or, here on the Stack Overflow site itself has in the part of inserting a tag, it shows everything that has related the letters that were typed in the field!

Only in my case I wanted him to pull the data from a table alone.

  • https://jqueryui.com/autocomplete/ da uma olhada :), ja q o mvc ja tem jquery msm

  • @Ciganomorrisonmendez is just like this, only it has to implement it to pull the data from a table in the database ?

  • Yes, see my answer. If anything is missing, just say so by comment.

2 answers

2

What you’re looking for is called Typeahead.

Usually the solution does not come alone: it accompanies another framework, like Bootstrap. There are some implementations of Typeahead for Bootstrap:

Or using only jQuery:

Depending on the implementation you choose, there may be a different Ajax format, usually asking for JSON. For these cases, implement a Action in Controller return 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 bank, but I’ll assume it’s the Entity Framework.

In case, let’s assume that you are bringing names of people and their respective Id’s (like the first example here, only with people instead of states). First let’s assemble 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);
    }
  • you could be a little more specific, I recently entered this programming area and I’m still a little lost, like could give me an example of how to link this script to the bank

  • Okay. See if you need anything else.

  • I will try to implement in my system, but still, I appreciate your help!

  • You could show me how you did on the part of your service and Repository ?

  • 1

    Service? Repository? Don’t use that! Read this here: http://answall.com/questions/51536/quando-usar-entity-framework-com-repository-pattern/80696#80696

0

In this case it does not pull from the database when typing, but pulls all the data and mounts the script needed for the autocomplete, that is, provides suggestions while 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>
<script src="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>



Browser other questions tagged

You are not signed in. Login or sign up in order to post.