jQuery UI autocomplete select event not working with mouse click

I tested it in all version of IE (inlcuding 9) and always ended up with an empty input-control after I selected the item using the mouse. This caused some headaches. I even went down to the source code of jQuery UI to see what happens there but didn’t find any hints either.

We can do this by setting a timeout, which internally queues an event in the javascript-engine of IE. Because it is guaranteed, that this timeout-event will be queued after the focus event (this has already been triggered before by IE itself).

select: function (event, ui) {
    var label = ui.item.label;
    var value = ui.item.value;
    $this = $(this);
    setTimeout(function () {
        $('#txtBoxRole').val(value);
    }, 1);
},

Thanks to @William Niu and firebug, I found that the select event parameter 'ui' contains the complete selected value: ui.item.value. So instead of depending on jquery UI to change the text of the textbox, which didn't happen if the user clicks with mouse, I just pick up the selected value from 'ui':

$("#reportname").autocomplete({
    select: function (event, ui) {
        var reportname = ui.item.value
        var thelinks = $('a.large:contains("' + reportname + '")').filter(
            function (i) { return (this.text === reportname) })
        window.location = thelinks[0].href
    };
})

To your 2nd question: "How can I differentiate between select events that are triggered by keyboard with the ones triggered by mouse?"

The event object in the jQuery UI events would include a .originalEvent, the original event it wrapped. It could have been wrapped multiple times though, such as in the case of Autocomplete widget. So, you need to trace up the tree to get the original event object, then you can check for the event type:

$("#reportname").autocomplete({
    select: function(event, ui) {
        var origEvent = event;
        while (origEvent.originalEvent !== undefined)
            origEvent = origEvent.originalEvent;
        if (origEvent.type == 'keydown')
            $("#reportfind").click();
    },
    ...
});

Tags:

Jquery Ui