Honatas / bootstrap-4-autocomplete

A simple autocomplete/typeahead for Bootstrap 4 and jQuery
MIT License
56 stars 31 forks source link

How to get current element in onSelectItem callback function #1

Closed hirenaspl closed 5 years ago

hirenaspl commented 5 years ago

Hello @Honatas ,

Can you please help with this and guide how to get current element where any autocomplete option is chosen. Have googled a lot and tried on my own but somehow I'm not able to figure that out. Below is the code:

$('input[type="text"].autocomplete').autocomplete({
            source: src,
            treshold: 2,
            onSelectItem: function(item) {
                console.log(item.value);
                console.log($(this));
                console.log($(this).find('input'));
                console.log(this);
            }
        });

The idea is that there can be more than one autocomplete control in a page and we need to get current control in onSelectItem callback function.

Thanks.

hirenaspl commented 5 years ago

Hello @Honatas,

I did like below and that seemed to be working for me:

$('input[type="text"].autocomplete').each(function (index, value) {
            var _ele = $(this);
            $(this).autocomplete({
                source: src,
                treshold: 2,
                onSelectItem: function(item) {
                    console.log(item.value);
                    console.log($(_ele).data('value-input'));
                }
            });
        });

I'll conclude later once all things I needed have been completed and that really works!

Please give your suggestion once you can.

Thanks.

Honatas commented 5 years ago

Hi @hirenaspl

Indeed, when you have more than one autocomplete on the same page, it is desirable to be able to recognize wich one has been changed when onSelectItem is fired.

Having to use a closure for this is not the best option, so I have added a second parameter to onSelectItem, it is the HTMLElement of the textfield. I've also updated the example, so take a look there and you'll be able to design a much better solution.

Please donwload v1.2.0 to get those changes. And thanks for contributing!

hirenaspl commented 5 years ago

Hello @Honatas

Many thanks - that really worked for me.