访问具有类似 ID 的输入的值


Accessing Value of Input with Similar Ids

我的页面上有几个动态创建的输入字段。在 JQuery 中,我试图获取我正在键入的值,以便我可以将该值传递给我的 php 脚本以填充自动完成。

例如:

 <input id="inventory_location_1">
 <input id="inventory_location_2">
 <input id="inventory_location_3">
 <input id="inventory_location_4">
 <input id="inventory_location_5">
 <input id="inventory_location_6">

如果我出于某种原因在"inventory_location_1"中输入文本,我不能使用 var strValue = $(this).val(); 来获取我正在输入的框的文本。Jquery 抛出一个错误。

这是我的完整 Jquery 脚本;

 $(function() {
        $('input[id^=inventory_location_]').autocomplete({
            source: function( request, response ) {
                $("#progressBar").show();
                var strValue = $(this).val();
                alert(asdf);
                $.ajax({
                    url: '{{ path('inventory_id_via_ajax_array') }}',
                    dataType: "json",
                    data: {
                        featureClass: "P",
                        style: "full",
                        maxRows: 12,
                        value: strValue
                    },
                    success: function( data ) {
                        if(data.responseCount <= 0){
                        }
                        response( $.map( data.responseData, function( item ) {
                            return {
                                label: item.name,
                                name: item.name,
                                value: item.name,
                                id: item.id
                            }
                        }));
                        $("#progressBar").hide();
                    }
                });
            },
            minLength: 2,
            select: function( event, ui ) {
                $("#progressBar").hide();
                $(this).val(ui.item.label);
            },
            open: function() {
                $( this ).removeClass( "ui-corner-all" ).addClass( "ui-corner-top" );
            },
            close: function() {
                $( this ).removeClass( "ui-corner-top" ).addClass( "ui-corner-all" );
            }
        });
    });

不知道该怎么办,我已经做了我能想到的一切。另外,如果您在我的脚本中看到其他不正确的内容,请告知。感谢您的帮助!!

这是一个简单的解决方法,当您在页面中的许多元素上初始化插件但需要访问每个特定元素时,它非常有效

 $('input[id^=inventory_location_]').each(function(){
           /* within $.each  "this" is the current element*/
           var ID=this.id; // can now pass  variable into plugin wherever you need it
             $(this).autocomplete({/* options*/});
});

您引用的行位于函数内,因此"this"关键字不再与输入字段相关。

此外,看起来您正在尝试从自动完成源函数中执行其他一些任务,我认为这不是正确的位置。