2012-10-31 95 views
1

我有一個來自JQUERY的自動完成,我想要產品的ID而不是我選擇的產品的名稱。從JQUERY獲取ID自動完成

這是完整的AUTOCOMPLETE:

<?php 

    // if the 'term' variable is not sent with the request, exit 
    if (!isset($_REQUEST['term'])) 
    exit; 

    // connect to the database server and select the appropriate database for use 
    include 'conexion2.php'; 

    // query the database table for client codes that match 'term' 
    $rs = mysql_query('SELECT id_cliente, nombrecliente FROM cliente where nombrecliente like "'. mysql_real_escape_string($_REQUEST['term']) .'%" order by nombrecliente asc', $conexio); 

    // loop through each name returned and format the response for jQuery 
$data = array(); 
    if ($rs && mysql_num_rows($rs)) 
    { 
    while($row = mysql_fetch_array($rs, MYSQL_ASSOC)) 
    { 
     $data[] = array(
      'label' => $row['nombrecliente'], 
      'value' => $row['nombrecliente'], 
     ); 
    } 
    } 

    // jQuery wants JSON data 
    echo json_encode($data); 
    flush(); 

我不知道如何取出ID當我選擇一個客戶端。如果我改變 '價值'=> $行[ 'id_cliente'],然後我得到的ID號碼在我的自動完成輸入....

+0

'value'=> $ row ['id_cliente']? –

+0

好的,我已經嘗試過,但它只是將客戶端的ID放在自動完成的INPUT中。我希望在自動填充的輸入中看到客戶端的名稱,同時還有客戶端的ID。 – user1757383

+0

如果我沒有記錯的建議包含ID和標籤...所以你必須切換然後... –

回答

1

在你的陣列,加入另一個項目:

'id' => $row['id_cliente'] 

然後,你需要添加一個隱藏的表單域來存儲你的ID。在你的jQuery(假設你使用jQueryUI的自動完成),您可以將源下的自動完成功能的一部分補充一點:

$('#autocomplete_input').autocomplete({ 
    source: '/path/to/lookup/php/file', 
    select: function(event, ui){ 
     $('#my_hidden_field').val(ui.item.id); 
    } 
}); 

然後,當你提交後讀你的形式,你會讀到ID代替的自動完成字段。

+0

感謝您的答案,但我到底需要把隱藏的表單域。我正在使用JQUERYUI自動完成。我應該把它放在腳本里面,或者我完全困惑? \t user1757383

+0

我已經編輯過我的JS。您顯然需要根據需要重新命名,但它現在應該更有意義。 隱藏的輸入會進入您的表單HTML

+0

非常感謝您的幫助.... – user1757383