Search code examples
jqueryjquery-uieventsautocompleteevent-propagation

jQuery autocomplete item click and event bubbling


How can I get the link click to trigger a select?

EDIT: Im refering to why doesnt the line $("a:contains('item2')").click(); trigger a autocomplete menu select?

<!doctype html>
<head>
    <title>Test</title>
    <script src="jquery-1.6.4.js"></script>
    <script src="jquery-ui-1.8.16.js"></script>
</head>

<script>

$(function() {

var menu = $('<div></div>')
    .attr('id', 'menu')
    .appendTo('body')
    .autocomplete({
        minLength: 0, 
        source: ['item1','item2'], 
        select: function(event, ui){
            alert('selected ' + ui.item.label);
        }
    })
    ;

$('<button></button>')
    .attr('id', 'open')
    .button({
        label: 'display menu'
        })
    .click(function() {
        menu.focus();
        menu.autocomplete("search", "");
    })
    .appendTo('body')
    .height(30)
    ;

$('<button></button>')
    .click(function() {
        $("#open").click();
        $("a:contains('item2')").click();
    })
    .appendTo('body')
    ;

});

</script>

<body>
</body>
</html>

Solution

  • This is caused by an "unfortunate" choice in the autocomplete widget -- it doesn't know what item you're selecting unless you've previously "hovered" it to make it the active menu choice.

    $('<button></button>')
      .click(function() {
        $("#open").click();
        $("a:contains('item2')").trigger('mouseover').trigger('click');
      })
      .appendTo('body');