jQuery UI Live

Jul21
Missing Image
By SiteCrafting Staff

jQuery has some awesome widgets, but all of them need to be attached after an element is added to the page. With some quick changes, your widget can be added dynamically to any element using $.live().

With the release of jQuery 1.3 developers have been give a great new tool to aid in dynamic development, namely live events. We discussed this back in march.


The other day I found myself attaching some jQuery UI widgets to some vague selectors to try and improve usability of form inputs (for instance, adding a date picker for all inputs with that have "date" in their name).

Typical Date Picker

$(function() {
	$(':text[name*=date]').datepicker();
});

This works very well, and in ways we didn't expect. But what about dynamically adding inputs to a page. You would have to reattach the UI widget each time. Or do you?

New Live Date Picker

We can employ live events to listen for clicks on dynamically inserted inputs. The downside is that you have to listen for a click, as the live function doesn't support onfocus events.

$(':text[name*=date]').live('click', function() {
	$(this).datepicker({showOn: 'focus'}).focus();
});

This code will add the date picker to any text box that has the word date in it. Note the ({showOn: 'focus'}).focus() portion. This is a way of causing the datepicker to listen for an event which we can invoke.

What's the catch?

You aren't getting something for nothing here. The problem with this approach is that you have to click the elements to bring up the first widget. Every time after that, tabbing through will work just fine. This is only a problem for the minor use case of keyboard input. But since most of the widgets focus on the mouse for input, this may not be a huge problem.


The other problem comes from my use of [name*=date], as this selector will also include [name*=update]. You could use [name*=date]:not([name*=update]), but then [name*=update_date] wont work. Again, this is pretty easy to get around, so I trust you can solve this on your own.


Dev

Back To Feed