2012-06-08 62 views
0

我有一堆字段(名字,姓氏等),我希望能夠將任何填充或部分填充的值傳遞到自動填充服務器端我可以在查詢中使用它們。使用多個字段值的jquery-ui自動完成

+0

另一篇文章,我有困難找到自己的網上線,並不得不工作,所以我發佈信息可以幫助其他人,或者有人可以提出更好的方法。 –

回答

0

我通過更新自動完成「源」來更改各個字段上的任何焦點更改或自動完成「選擇」事件。

jQuery('#people_new_user input[type="text"]').each(
    function(index, element) { 
     var field = element.name; 
     jQuery(element) 
      .focus(setSourceUser) 
      .autocomplete({ 
      source: "/cf/AutoComplete/People?current="+field, 
      select: selectUser 
     }); 
    }); 

上面的代碼建立了一個被稱爲「setSourceUser」和用於自動完成的處理程序「焦點」的事件處理程序「中選擇」事件被稱爲「selectUser」。

function setSourceUser(event) 
{ 
    var endPart = ""; 
    jQuery('#people_new_user input[type="text"]').each(
    function(index, ielement) { 
     var ifield = ielement.name; 
     var ival = ielement.value; 
     if (ival != '') 
     { 
      endPart += '&field=' + ifield; 
      endPart += '&value=' + ival; 
     } 
    }).each(
    function(index, element) { 
     var field = element.name; 
     jQuery(element) 
       .autocomplete("option", "source", 
        "/cf/AutoComplete/People?current="+field+endPart); 
    }); 
} 

上述「setSourceUser」函​​數從所有字段的所有值(在第一個「每個」功能),並建立所述源的「endPart」,然後建立自動完成「源」選項爲每個領域。我不會顯示「選擇」回調,因爲它會處理與此問題無關的其他內容,然後調用「setSourceUser」。源代碼的結果是/cf/AutoComplete/People?current=last_name&field=first_name&value=p&field=last_name&value=tomblin以及自動完成自身提供的「term」值。在「LIKE」中,我的函數(在這種情況下用Mason和Perl編寫)使用&field=foo&value=bar對(跳過字段== current,因爲自動完成在term中傳遞更多當前值) sql語句。然後我用JSON返回找到的結果。 (如果有超過50個結果,我不打擾,因爲名單會太長。)

% $r->content_type('application/json'); 
<% JSON::to_json(\@suggestions, { utf8 => 1, allow_blessed => 1, 
    convert_blessed => 1, }) |n %> 
% $m->abort; 
<%ARGS> 
@field => undef 
@value => undef 
$current => undef 
$term => undef 
</%ARGS> 
<%INIT> 
use RTx::SearchBuilder::Records::Peoples; 

$current =~ s/people_//g; 

my $people = RTx::SearchBuilder::Records::Peoples->new(Handle => CFHandle()); 
my $fn = scalar(@field); 
for my $i (0...$fn-1) 
{ 
    my $f = $field[$i]; 
    next if !defined($f); 
    my $v = $value[$i]; 
    if ($f ne $current) 
    { 
    $people->Limit(
     FIELD  => $f, 
     OPERATOR => 'LIKE', 
     VALUE  => '%'.$v.'%', 
     ENTRYAGGREGATOR => 'AND'); 
    } 
} 

$people->Limit(
    FIELD  => $current, 
    OPERATOR => 'LIKE', 
    VALUE  => '%'.$term.'%', 
    ENTRYAGGREGATOR => 'AND'); 

my @suggestions; 

# If there are too many results, skip it and make them narrow it down a bit 
# more 
if ($people->Count < 50) 
{ 
    while (my $person = $people->Next) 
    { 
    my $suggestion = { label => $person->$current, value => $person }; 
    push @suggestions, $suggestion; 
    } 
} 
</%INIT>