JQuery UI自动完成通过JSON发送额外的术语

时间:2012-12-18 06:51:18

标签: jquery jquery-ui jquery-autocomplete

我从jQuery UI文档中获取了大部分代码。 我想添加请求变量,以便发送<input> id。

输入看起来像这样:

<input size="50" class="attr_values" name="msrp" id="msrp" />

现在这里是jquery。在.autocomplete源$ .getJSON里面我尝试使用“this.id”,它不起作用。我怎样才能让它发挥作用?

$(document).ready(function() { 
    // 2 string parsing functions
    function split( val ) {
        return val.split( /,\s*/ );
    }
    function extractLast( term ) {
        return split( term ).pop();
    }


    $( '.attr_values' )
        // 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( 'controllers/core_data/ajax/core_data.php', {
                    'attr_name' : this.id, // THIS DOESN'T WORK
                    'term': extractLast( request.term )
                }, response );
            },
            search: function() {
                // custom minLength
                var term = extractLast( this.value );
                if ( term.length < 2 ) {
                    return false;
                }
                // var attr_name = this.id;
            },
            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;
            }
        });

 });

另请注意,我已将此应用于“.attr_values”类,而不是像示例show那样应用于某个特定ID。我有一大堆字段,每个字段都有不同的ID。这就是我需要将id和术语发送到php脚本的原因。这样它就知道哪个表可以查看该词。

2 个答案:

答案 0 :(得分:1)

thisgetJSON回调中不再引用原始集合。尝试向上钻取以获得原始元素:

source: function( request, response ) {
    $.getJSON( 'controllers/core_data/ajax/core_data.php', {
        'attr_name' : this.element[0].id,
        'term': extractLast( request.term )
    }, response );
},

此处的上下文this指的是您正在评估autocomplete函数的source对象。我们可以使用element属性来获取相应的jQuery集合,然后从中找到id。

答案 1 :(得分:-1)

尝试给这个..

$(this).attr('id');