2012-09-11 5 views
2

jQuery의 자동 완성 위젯을 시험해보고 벽에 부딪혔다. 일부 입력/안내에 감사드립니다.두 필드에 대한 jQuery/JSON 자동 완성

기본적으로 누군가가 사람의 이름을 입력하는 양식이 있습니다 ... jQuery는 데이터베이스에 쿼리를 수행하고 일치하는 항목을 제안합니다. 이 양식에는 이름 필드와 숨겨진 ID 필드 인 JSON 데이터에서 채워야하는 두 개의 필드가 있습니다. 지금까지는 제안 만하고 이름 필드를 채울 수 있지만 선택하면 숨겨진 ID 필드를 업데이트하는 데 아무런 운이 없었습니다. jQuery 코드에서 뭔가 중요한 것이 빠져 있어야하지만 알아 내지 못했다. "select"이벤트를 사용하여 값을 설정하려했지만 행운이 없었습니다. 여기

$(function() { 

     $("#proj_poc").autocomplete({ 
      source: function(request, response){ 
       $.getJSON("/includes/AJAX/GetContactNames.php?callback=?", request, function(data){ 
        var suggestions = []; 
        $.each(data, function(i, val){ 
         suggestions.push(val.contacts); 
        }); 
        response(suggestions); 
       }); 
      }, 
      minLength: 2, 
      select: function(event, ui){ 
         //Should display user ID a 
         alert(ui.item.id + ui.item.contacts); 

      } 

     }); 

}); 

//Initiate the session 
session_start(); 

//Load custom classes 
    include_once ('../../ops.inc.php'); 

//Get the search term from GET 
    $param = $_GET['term']; 

//Create new dblink class and connect to db 
    $uplink = new dblink(); 
     $uplink->connect(); 

//Create new dbcontrol class  
    $control = new dbcontrol(); 

//Set the query to select ID and CONCAT'd NAME from Contact Table 
    $control->query = "SELECT `id`, CONCAT_WS(\" \",`firstname`,`lastname`) AS 'contacts' FROM `addressbook` WHERE `firstname` REGEXP '^$param'"; 

//Execute the query 
    $control->execute(); 

//Set an iterator value to 0  
    $i = 0; 

//Get the results into array, then iterate. 
    while($row = $control->toAssocArray()){ 

     foreach($row as $column=>$value){ 
      $results[$i][$column] = $value; 
     } 

     $i++; 

    } 

//Set the response string and encode for json 
    $response = $_GET['callback']."(".json_encode($results).")"; 

//Display the response string 
    echo $response; 

//Disconnect from the database 
    $uplink->disconnect(); 

//Destroy classes 
    unset($uplink, $control); 

출력 GetContactNames.php

에서 관련 PHP이다 : 여기
<div id="formblock" class="stack"> 
    <label>Project POC: <span class="error" name="proj_poc_error" id="proj_desc_error">This field is required.</span></label> 
    <input type="text" name="proj_poc" id="proj_poc"> 
    <input type="hidden" name="proj_poc_id" id="proj_poc_id" value="NOT SET"> 
</div> 

가 관련 jQuery 코드이다 : 여기

는 관련 FORM 코드 GetContactNames.php 결과는 다음과 같습니다.

([{"id":"1","name":"Santa Clause"},{"id":"2","name":"Joe Blow"}]) 

의견이 있으십니까?

답변

3

원본 함수에서 빌드하는 데이터 구조에는 레이블과 값 필드가있는 개체가 있어야합니다. 레이블 필드는 자동 완성 메뉴에 표시되는 것으로, 값을 선택하면 값은 텍스트 필드에서 값으로 설정됩니다. 값이 실제로 단지가 될 것 텍스트 필드에 복사하는 동안,

이 예에서
success: function(data) { 
      response($.map(data, function(item) { 
       return { 
       label: item.username+" ("+item.firstname+" "+item.lastname+")", 
       value: item.username 
      }; 
    } 

, 표시된 값은 사용자 이름 + 성과 이름이 될 것이다 : 여기

는 예를 들어, 검색하는 사용자입니다 사용자 이름.

그런 다음 당신은 선택 기능에서이 작업을 수행 할 수 있습니다 : 당신이 준 JSON에서, 어떤이이기 때문에 val.contacts 변수에서 유래없는 경우

select: function(event, ui) { 
    alert(ui.item.value); 
} 

또한, 코드에서, 내가 볼 수 없습니다 " 연락처 "필드에 ...

희망이 도움이됩니다.

관련 문제