Skip to content Skip to sidebar Skip to footer

How To Prevent Closing The Menu After A Select?

I am using the jQuery Autocomplete widget and, inspired by this question in order to prevent closing the menu after select, I came up with this code: $(#input_field).autocomplete({

Solution 1:

Unfortunately there's no option/method in current jQuery UI to handle this issue. The method you trying to use is for older versions of jQuery UI. In current version ui.item doesn't have proporties you trying to access. It only has {"label":"Java","value":"java"} inside, so that's why you have an error.

So to make it works you'll need some sort of hack. By inspecting jQuery UI source code I found that the easiest and most reliable way to do this is to override public close method with out custom method. It's really easy to do if you never need to close autocomplete:

$("#input_field").data('autocomplete').close = function() {};

But it's more complicated if you want to prevent closing only when item is selected with mouse:

// custom close method
(function(){
    var instance = $("#input_field").data('autocomplete');
    var origClose = instance.close, mouseFlag;

    // capture mouse events
    instance.menu.element.on('mousedown', function() {
        mouseFlag = true;
    });
    instance.close = function(e) {
        if(!mouseFlag) {
            // call original method if drop isn't closed by mouse
            origClose.apply(this, arguments);
        } else {
            // clean flag in setTimeout to avoid async events
            setTimeout(function(){
                mouseFlag = false;    
            },1);
        }
    }
}());​

Working JSFiddle


Post a Comment for "How To Prevent Closing The Menu After A Select?"