How not to show jQuery UI autocomplete input the HTML of the variable?

Asked

Viewed 465 times

0

I’m using the autocomplete of jQuery. I got him to play HTML, but the HTML is displayed on input.

I need to format my search like I did: inserir a descrição da imagem aqui

When I click, however, the result is displayed like this: inserir a descrição da imagem aqui

Should not display tags. How do I?

This is my code:

$("form#busca #campo-busca").autocomplete({
  minLength: 3,
  source: 'autocomplete.php',
  html: true
});
<form id="busca">
  <input type="text" placeholder="O que você está procurando?" name="busca" id="campo-busca">
  <input type="submit" value="buscar">
  <br>
</form>

And here the PHP:

$termodeBusca = $_GET['term'];

//Retorna categorias 
$sqlCategorias = mysqli_query($conn, "SELECT nome FROM categorias WHERE nome LIKE '%{$termodeBusca}%' AND status = 1 GROUP BY nome LIMIT 10");

if(mysqli_num_rows($sqlCategorias) != 0){
    while($nomeCategoria = mysqli_fetch_array($sqlCategorias)){
        $resultado[] = "<b>Categoria</b> {$nomeCategoria['nome']}";
    }
}

//Retorna categorias 
$sqlClientes = mysqli_query($conn, "SELECT nome FROM clientes WHERE nome LIKE '%{$termodeBusca}%' AND status = 1 GROUP BY nome LIMIT 100");

if(mysqli_num_rows($sqlClientes) != 0){
    while($nomeCliente = mysqli_fetch_array($sqlClientes)){
        $resultado[] = "<i>{$nomeCliente['nome']}</i>";
    }
}

//Devolve ao Ajax
echo json_encode($resultado);
  • Aryana Valcanaia, check if you remove tags: From $result[] = "<b>Category</b> {$nameCategory['name']}"; For $result[] = "Category - {$nameCategory['name']}";.

  • @pss1support Hi! Yes, if I take the tags away, the input is not presented. The problem is that I need to keep the formatting of the first image :/

  • @Aryanavalcanaia already tried to use the method _renderItem ?

  • hi @wmsouza! I tried yes, I don’t know if I didn’t implement it right or I couldn’t implement it, but it didn’t work :/ I believe that with it I need to return an array within my $result[] passing a value to be displayed by the input and another by the search results. I tried everything that is way and did not roll. I also can not find example as what I need :(

2 answers

0


Reading the documentation of Autocomplete, I couldn’t find anything talking about the option html: true/false, but talks about the extension jquery.ui.autocomplete.html.js created by Scott González.

You must return the data on JSON and use the method _renderItem, see below an example:

Filing cabinet php autocomplete.

//Retorna categorias 
$sqlCategorias = mysqli_query($conn, "SELECT id, nome FROM categorias WHERE nome LIKE '%{$termodeBusca}%' AND status = 1 GROUP BY nome LIMIT 10");

if(mysqli_num_rows($sqlCategorias) != 0){
    while($Categorias = mysqli_fetch_array($sqlCategorias)){
        $resultado[] = array(
            "id" => $Categorias['id'],
            "value" => "<b>Categoria</b> {$Categorias['nome']}"
        );
    }
}

Javascript

$( "#campo-busca" ).autocomplete({
  minLength: 0,
  source: 'autocomplete.php',
  focus: function( event, ui ) {
    $( "#campo-busca" ).val( ui.item.value );
    return false;
  },
  select: function( event, ui ) {
    $( "#campo-busca" ).val(ui.item.value);
    return false;
  }
})
  .autocomplete( "instance" )._renderItem = function( ul, item ) {
  return $( "<li>" )
    .data("item.autocomplete", item)
    .append( "<div>"+item.tipo+": " + item.value + "</div>")
    .appendTo( ul );
};

See working:

var categorias = [
  {
    id: 1,
    tipo: '<b>Categoria</b>',
    value: 'Imóvel'
  },
  {
    id: 2,
    tipo: '<b>Categoria</b>',
    value: 'Móveis'
  },
  {
    id: 3,
    tipo: '<b>Categoria</b>',
    value: 'Carros'
  },
  {
    id: 4,
    tipo: '<b>Categoria</b>',
    value: 'Motos'
  }
];

$( "#campo-busca" ).autocomplete({
  minLength: 0,
  source: categorias,
  focus: function( event, ui ) {
    $( "#campo-busca" ).val( ui.item.value );
    return false;
  },
  select: function( event, ui ) {
    $( "#campo-busca" ).val(ui.item.value);
    return false;
  }
})
.autocomplete( "instance" )._renderItem = function( ul, item ) {
  return $( "<li>" )
    .data("item.autocomplete", item)
    .append( "<div>"+item.tipo+": "+ item.value + "</div>")
    .appendTo( ul );
};
<link href="https://code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css" rel="stylesheet" type="text/css" />
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<input type="text" id="campo-busca">

  • 1

    That’s right! It worked right, thank you very much. I had some implementation problems. His example was very close to what he had been trying to implement with renderItem. Even I was having difficulties implementing its code running together with my project (isolated worked). Here was the problem: ID conflict. I discovered that in the project there were two Ids with the same name. It is a tip for other people who are hitting themselves hahaha I lost hours in a silly. Thank you again! :)

0

Well, one of the approaches may be the following:

$("form#busca #campo-busca").autocomplete({
  minLength: 3,
  source: 'autocomplete.php',
  /** 
   * Sugestão de uma das possíveis soluções.
   */
  select: function( event, ui ) {
    /**
     * Considerando que podemos acessar o valor assim: ui.item.value
     */
    $("form#busca #campo-busca").val( ui.item.value );
    // ou
    $("form#busca #campo-busca").html( ui.item.value );

    return false;
  },
  html: true
});

NOTE: interesting to analyze the possibility of using the resources in a way to reuse. This way think about creating the component inside a plugin [Jonathan Chaffer, Karl Swedberg - 2013, ___ 8 - Developing Plugins, 234 p.] and using as a $.widget(){}.

the plugin file: app-your-plugin.js

/*@!
 * @auth: Paulo Sérgio da Silva
 * @email: [email protected]
 * @plugin: app-seu-plugin.js 
 * @description: O objetivo de centralizar as funções genéricas para o
 *  carregamento e apresentação do autocompletar em ????????.
 *
 * Autocompletar Categoria v1.0.0 (http://www.??????/)
 * Copyright 2011-2015 ????, Pub.
 * Licensed under MIT ()
 */

if (typeof jQuery === 'undefined') { 
    throw new Error('Component Type Fields\'s JavaScript requires jQuery') 
}

/**
 * Criando o plugin
 */
(function($){ 

    var SeuPlugin = function(){
        this.alertTestPlugin = function(){
          console.log("alertTestPlugin: Testando o plugin jQuery!");
          alert("alertTestPlugin: Testando o plugin jQuery!");
          return false;
        };

        this.createWidget = function() {
             /** Criando do widget */
             $.widget( "custom.seuComponenteAutocompletar", $.ui.autocomplete, {
              _create: function() {
                //Implementar o comportamento de seu interesse
              },
              _renderMenu: function( ul, items ) {
                //Implementar a aparência de seu meu
              }
            });
        }
    };

    $.SeuPlugin = new SeuPlugin();
    $.SeuPlugin.prototype = SeuPlugin;

})(jQuery); 

/**
 * 
 */
$.SeuPlugin.createWidget();

Load your plugin:

<link href="https://code.jquery.com/ui/1.12.1/themes/smoothness/jquery-ui.css" rel="stylesheet" type="text/css" />
<script src="https://code.jquery.com/jquery-3.1.0.js"></script>
<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
<!-- Carregar o seu plugin -->
<script src="../plugins/PATH_PARA_SEU_PLUGIN/app-seu-plugin.js"></script>

Using its component:

$("form#busca #campo-busca").seuComponenteAutocompletar({
  delay: 0,
  minLength: 3,
  source: 'autocomplete.php',
  html: true
});

Reference:
[Jonathan Chaffer, Karl Swedberg - 2013], Copyright 2013 Packt Publishing, Learning jQuery Fourth Edition: Better Interaction, design, and web Development with simple Javascript Techniques. Available at: < https://www.packtpub.com/web-development/learning-jquery-fourth-edition >. Accessed: Nov 25, 2017.
[jqueryui], Autocomplete #Categories: jQuery User interface - Autocomplete. Available in: < https://jqueryui.com/autocomplete/#Categories >. Accessed: Nov 25, 2017.

Browser other questions tagged

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