简体   繁体   中英

How to get the $(this) to work in JQueryUI autocomplete

Here is a fiddle example

I have trouble getting the $(this) to work in the source function with jQueryUI autocomplete. The console shows that the search input isn't able to get its data attribute 'name' before sending out an Ajax request. Is there any way to pass the variable "name" to data ?

$('.input').autocomplete({
    source: function (request, response) {
        var name = $(this).data('name');
        console.log(name);
        $.ajax({
            url: url,
            dataType: "json",
            data: {
                'q': request.term,
                'field': name
            },
            success: function (data) {
                response($.map(data.query.results.json.json, function (item) {
                    return {
                        label: item.name,
                    }
                }));
            }
        });
    },
    minLength: 2,
    select: function (event, ui) {
        $(this).val(ui.item.label);
        $(this).val(ui.item.label);
    },
    open: function () {
        $(this).autocomplete("widget").width(400)
    }
});

You should use this.element to access corresponding input element. this points to the autocomplete instance itself:

var name = $(this.element).data('name');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM