jQuery UI Autocomplete disable Select & Close events

前端 未结 5 1915
离开以前
离开以前 2020-12-06 10:33

I\'m using jQuery UI\'s Autocomplete slightly differently than it was probably created to do.

Basically I want to keep all the same functionality, the only differenc

5条回答
  •  执笔经年
    2020-12-06 10:41

    Going with $input.data("autocomplete").menu.options.selected = function(){} caused value not holding after selecting different item (our implementation needed to append to the end. Possibly needed just to add e.preventDefault() or return false before append code). So I just made a switch in the close event. example with putting external variable and writing own method is better, but also did not like it. I first though of calling method manually with passing a parameter when need to close autocomplte by hand. (in our implementation customer required the list to be open when clicking the items, but close when mouse leaves the textbox container.

    So I just attached autocomplete to the textbox`s element container and attached mouseenter and mouseleave. To determine if it should close, I used the jQuery(this).data("canClose") custom variable. Basically, what it does, is just reopening the autocomplete with search method when variable is 'false'.

    Here is the final code:

    element.autocomplete({
                    minLength:0,
                    source: source,
                    appendTo: element.parent(),
                    close: function () {
                        if (!jQuery(this).data("canClose")) {
                            jQuery(this).autocomplete('search', '');
                        }
                        return false;
                    }
                });
                element.mouseenter(function () {
                    element.data("canClose", false);
                    jQuery(this).autocomplete('search', '');
                });
                element.parent().mouseleave(function () {
                    element.data("canClose", true);
                    element.delay(2000).autocomplete("close");
                });
    

    if You need to do the append instead of replace value add the select handler in the constructor:

     select: function (event, ui) {
                        var text = element.text().trim();
                        if (text.length > 0 && !text.endsWith(",")) {
                            text += ", ";
                        }
                        jQuery(this).text((text + ui.item.label));
                        jQuery(this).focus();
                        return false;
                    }
    

提交回复
热议问题