Load related values in input text field correctly using Typeahead.js

Asked

Viewed 95 times

0

I’m using the plugin Typeahead.js in my project and would like to modify my script so that it can fill the input text field correctly after a select box option is selected. As a reference I created a html page to demonstrate the doubt described here.

In the post "How to load a value into a DIV after selecting an option in the dropdownlist of an input text using Typeahead and Ajax?" demonstrates a doubt that has been resolved with the help of the user Sam.

Through this solved doubt I decided to insert a select box where it has the function of filling the input text #product which in turn loads values based on the ID of the selected category.

Below, I will show the Mysql table that is called (products) where it contains records that are filled in the input text #products:

produtoID | categoriaFK (Foreing Key) | nomeProduto          | imagem
------------------------------------------------------------------------
01        | 1 (calçados)              | Tênis Adidas         | img_01
02        | 1 (calçados)              | Tênis Nike           | img_02
03        | 2 (Vestuários)            | Camisa Básica Branca | img_03
04        | 2 (Vestuários)            | Camisa Azul          | img_04
05        | 2 (Vestuários)            | Calça Jeans          | img_05

Below is the Ajax script that sends a request for php script code. This script has been modified according to this topic How to load a value into a DIV after selecting an option in the dropdownlist of an input text using Typeahead and Ajax? by the user @Sam where I adapted it to the format I’m working on:

 $(document).ready(function(){
var produtos;
var nomes = []; // array
var lista = {}; // objeto

$('#categoriaFK').on('change', function(){

var queryID = $(this).val();

   $.ajax({
    url:"fetch.php",
    method:"POST",

    data:{categoria:queryID},
    dataType:"json",
success:function(data){
console.log(data);

$.each(data, function(i, optionHtml){
              $('#produtos').append(optionHtml);
           });

$("#imagem").empty('');
$(".typeahead").val('');
produtos = data;

 }
 });

 $('.typeahead').typeahead({

  source: function(query, result)
  {
   $.each(produtos, function(idx, item){

      if(!~nomes.indexOf(item.nomeProduto)) nomes.push(item.nomeProduto);
      lista[item.nomeProduto] = item.imagem;
   });
   return result(nomes);
},
  afterSelect: function (data) {
  var img = lista[data];

   $('#imagem').html(img);


},

 });

}); 
});

Finally, the php script code (fetch php.) which sends the result in json to Ajax script:

<?php
require_once 'dbConfig.php';

if(isset($_POST["categoria"])){
    $request = $db->real_escape_string($_POST["categoria"]);

    $query = "
        SELECT * FROM produtos WHERE categoriaFK = ".$request."
    ";

    $result = $db->query($query);
    $data = array ();

    if ( $result->num_rows > 0 )
    {
        while($row = $result->fetch_assoc ())
        {
            $data[] = $row;

        }

 header("Content-type: application/json; charset=utf-8 cache-control: no-cache, no-store, must-revalidate");
 echo json_encode($data);
 exit();
    }
}
?>

In the case, as mentioned above, I created a html page to demonstrate the functioning of the above code but when the user selects the select box "Category, the input text field #products is filled out correctly using Typeahead.js but if the user selects some other option in the select box field without updating the page, the input text field loads all of the column records "nomeProduct" table products.

In case what would be the best way for me to modify Ajax so that it fills the input text field #products correctly without having to update the page to do so?

1 answer

0


After a few adjustments I managed to find a solution. I kept the "list" variable and made an adjustment in the Typeahead afterSelect event where after selecting an option within the input text the afterSelect event sends a value related to the selected item into the #image div. This solution can be seen in operation here.

Follow the adjusted script:

<script type="text/javascript">

    var produtos;
    var lista = {}; // cria o objeto

        $ ( function ()
        {
            $('#categoriaFK').on('change', function(){
                var queryID = $(this).val();

                $.ajax({
                    url:"fetch.php",
                    method:"POST",
                    data: {
                        categoria: queryID
                    },
                    dataType:"json",
                    success:function(data)
                    {
                        console.log(data);

                        $("#produtos").val ('');

                        produtos = data;

                    }
                });
            });

            $('#produtos').typeahead({
                source: function ( query, result )
                {
                    result ( $.map(produtos, function (item)
                        {
                            return item.nomeProduto;

                        }
                    ));

                },

                /* O ajuste foi feito aqui no evento afterSelect */

                  afterSelect: function(data) {
       $.each(produtos, function(idx, item){

      lista[item.nomeProduto] = item.imagem;
   });


   var img = lista[data];

   $('#imagem').html(img);


  },                        
            });

        });

</script>

Finally, this was the solution I could find. If anyone suggests a more optimized modification, feel free. Thanks!

Browser other questions tagged

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