使用autocomplete.js中的值的id填充隐藏的输入

时间:2016-02-23 07:04:54

标签: php jquery html mysql autocomplete

我现在正在工作的是当我输入一个人的姓名时自动完成。我需要的是当我选择名称时自动用该人的id填充一个隐藏字段。

我的代码:

<form action="cadastroAdm.php" method="post" name="clientForm">
      <input type="text" name="clienteId" id="clienteId">   
      <input type="text" name="clienteNome" id="clientes"> 
</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);  
        });

        $('#clientes').autocomplete({
        source: dados,
        minLength: 3,   

          select: function(event, ui) {

            $('#clienteId').val(ui.item.id);
            console.log(ui.item.id);                
          },

            });
        });
});  
  

retornar_cliente.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));
?>

在控制台日志中我只是收到“undefined”.. 我做错了什么?

2 个答案:

答案 0 :(得分:1)

只需更改您的查询:

"SELECT clienteNome, clienteId as id FROM cliente ORDER BY clienteNome"

使用以下方法更改JS中的变量:

ui.item.clienteId

修改:

您没有在id数组中推送dados

请参阅此链接:http://jqueryui.com/autocomplete/#remote

答案 1 :(得分:0)

问题解决了......按照我使用的代码:

  

retornar_cliente.php

<?php require_once("conexao/conexao.php"); ?>
<?php
$term = trim(strip_tags($_GET['term']));//retrieve the search term that autocomplete sends

$qstring = "SELECT clienteNome as value,clienteId as id FROM cliente WHERE clienteNome LIKE '%".$term."%'";

 $consulta_tr = mysqli_query($conecta, $qstring);
    if(!$consulta_tr) {
        die("erro no banco1");
    }

while ($row = mysqli_fetch_array($consulta_tr,MYSQL_ASSOC))//loop through the retrieved values
{
        $row['value']=htmlentities(stripslashes($row['value']));
        $row['id']=(int)$row['id'];
        $row_set[] = $row;//build an array
}
echo json_encode($row_set);//format the array into json data
?>
  

HTML

<form action="cadastroAdm.php" method="post" name="clientForm">
      <input type="text" name="clienteId" id="clienteId">   
      <input type="text" name="clienteNome" id="clientes"> 
</form>
  

jquery的

$(document).ready(function() {

        $('#clientes').autocomplete({
        source: 'php/retornar_cliente.php',
        minLength: 3,   

          select: function(event, ui) {

            $('#clienteId').val(ui.item.id);            
                 },
            });     
        });