Send id to an Hidden field by clicking on an item in the.js autocomplete

Asked

Viewed 469 times

1

I need to send the client id to an Hidden field by clicking on its name that is brought by the jquery autocomplete. The autocomplete is already working ok.. what I really need is to click send the ID to the Hidden field.

html

<form class="form-horizontal" action="cadastroAdm.php" method="post" name="clientForm">

          <div class="form-group">
              <div class="col-md-12">
                  <label for="clienteNome" class="control-label">Nome do cliente</label>
                  <input type="text" name="clienteNome" id="clientes"  class="form-control" placeholder="Nome do cliente">

            </div>
          </div>
                  <input type="hidden" name="clienteId" id="clienteId" >      
      </form>

jquery

$(document).ready(function() {
// Captura o retorno do retornaCliente.php
    $.getJSON('php/retornar_cliente.php', function(data){
    var dados = [];
    // Armazena na array capturando somente o nome do EC
    $(data).each(function(key, value) {
        dados.push(value.clienteNome);
    });
    // Chamo o Auto complete do JQuery ui setando o id do input, array com os dados e o mínimo de caracteres para disparar o AutoComplete
    $('#clientes').autocomplete({ source: dados, minLength: 3});
    });
});// JavaScript Document

ret_client.php

<?php
$hostname = "";
$user = "";
$pass = "";
$basedados = "";
$pdo = new PDO("mysql:host=localhost; dbname=adv; charset=utf8;",'root','');
$dados = $pdo->prepare("SELECT clienteNome, clienteId FROM cliente ORDER BY clienteNome");
$dados->execute();
echo json_encode($dados->fetchAll(PDO::FETCH_ASSOC));
?>

1 answer

2

Use the function select, it is called every time a menu item is selected.

$('#clientes').autocomplete({
  select: function(event, ui) {
    $('#clienteId').val(ui.item.id);
    console.log('Objeto selecionado: ' + ui.item);
  }
  source: dados,
  minLength: 3
});
  • this way it sends the name to the input.. but I need the ID of that name

  • I put it wrong, just switch to the property you want. The item is your element. See the edited answer.

  • I switched but nothing happened :|

  • That’s right my function . each?

  • on the console only appears "Undefined"

  • Try to see what’s in the ui only. And navigate between properties. By default the item will bring the objeto selected from the list you added to source.

Show 1 more comment

Browser other questions tagged

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