jQuery-ui / auto-complete / getJSON - 如何将元素的id传递给外部PHP

时间:2012-02-08 19:36:45

标签: jquery jquery-ui jquery-ui-autocomplete getjson

我将jQuery-ui自动完成功能绑定到我页面中的多个元素,因为我希望在不同的字段中使用相同的选项集自动完成。类似的东西:

<input class='myclass' id='myid1' name='field1' type='text' />
<input class='myclass' id='myid2' name='field2' type='text' />
<input class='myclass' id='myid3' name='field3' type='text' />

我正在使用jquery-ui autocomplete中的“Multiple Remote”选项,所以javascript看起来像这样:

$(".myclass")
    // don't navigate away from the field on tab when selecting an item
        // don't navigate away from the field on tab when selecting an item
        .bind( "keydown", function(event) {
            if (event.keyCode === $.ui.keyCode.TAB &&
                $(this).data("autocomplete").menu.active) {
                event.preventDefault();
            }
        })
        .autocomplete({
            source: function( request, response ) {
                $.getJSON("search.php"
                         ,{ term:extractLast(request.term) }
                         ,response);
            },
            search: function() {
                // custom minLength
                var term = extractLast(this.value);
                if (term.length < 1) {
                    return false;
                }
            },
            focus: function() {
                // prevent value inserted on focus
                return false;
            },
            select: function( event, ui ) {
                var terms = split( this.value );
                // remove the current input
                terms.pop();
                // add the selected item
                terms.push(ui.item.value);
                // add placeholder to get the comma-and-space at the end
                terms.push("");
                this.value = terms.join(", ");
                return false;
            }
        });

一切都很好。 但我想将id作为第二个参数传递给getJSON。我怎么能做到这一点?

我知道如何在 $。getJSON 语句中添加第二个参数,但我无法获取事件触发器的“id”。我尝试了 $(this).attr('id'),但它给了我 undefined 。有什么建议吗?

感谢。

1 个答案:

答案 0 :(得分:4)

请注意,“source”回调中的this是插件的实例,而不是INPUT元素。

对INPUT的引用实际上保存在“element”属性的插件实例中。
这样做:

source: function( request, response ) {
     var inputID = this.element.attr('id');
     $.getJSON("search.php"
        ,{ term:extractLast(request.term), id: inputID }
        ,response);
},

<强> DEMO