Josh Smith
Josh Smith

Reputation: 15028

Can't listen on events within the jQuery UI Autocomplete menu

The problem:

I've tried listening on several different types of events within the jQuery UI autocomplete menu, for example .on('click') and .on('submit').

None of the events are caught. In the case of the click event, the event isn't registered at all. And in the case of the submit, I try preventing default on the form id, but to no avail.

Essentially my use case for this is that I'm using the autocomplete to show possible options for an input, and appending an extra li to the menu on the open event with a button/form to add another option.

Can I simply not listen on events for some reason within autocomplete, other than the specified events like select?

jsFiddle

Here's a short jsFiddle demo.

Upvotes: 2

Views: 369

Answers (1)

Amin Eshaq
Amin Eshaq

Reputation: 4024

You'll need to delegate the click event because the button element is added dynamically and isn't present when you bind it with the .on() event binder.

$('body').delegate('#add-from-search','click', function() {
    console.log('clicked');
});

Look at this fiddle

From Jquery on.() docs

Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on(). To ensure the elements are present and can be selected, perform event binding inside a document ready handler for elements that are in the HTML markup on the page. If new HTML is being injected into the page, select the elements and attach event handlers after the new HTML is placed into the page. Or, use delegated events to attach an event handler, as described next.

Upvotes: 1

Related Questions