- news (347)
- links (345)
- jQuery Plugins (61)
- jQuery Code Snippets (34)
- jQuery and JavaScript (21)
- plugins (17)
- jQuery News (17)
- Uncategorized (16)
- Media (13)
- jQuery Mobile (11)
- jQuery and CSS (10)
- jQuery Utilities (9)
- jQuery and Ajax (9)
- Random jQuery Stuff (9)
- jQuery Functions (8)
- jQuery Articles (8)
- images (7)
- jQuery (7)
- jQuery Tutorials (7)
- jQuery and HTML (6)
- Javascript Libraries (6)
- jQuery and WordPress (6)
- jQuery Events (6)
- jQuery Testing (6)
- jQuery Image Scripts (5)
- jQuery Knob demo
- Magic Zoom : JavaScript image zoom tool
- jQuery Slider plugin
- jQuery Image Slider V3
- 翻訳:HTML5モバイルWebフレームワークの比較 - きしだのはてな
- Learning Advanced JavaScript
- Shadowbox.js Media Viewer
- Lazy Load Plugin for jQuery
- A Pure CSS3 Cycling Slideshow | Smashing Coding
- URL Decoder. Decode and parse URL online. Javascript jQuery plugin.
- minjs - Minimalist JavaScript
- 13 Great Flickr Galleries to Integrate into Your Site - The Designed
- jQuery Form Input Hints Plugin (Rob Volk's Blog)
- jQuery Mobile | jQuery Mobile
- Thickbox - ColorBox - FancyBox - ShadowBox Comparison - SoftwareProjects : Internet Marketing Services
- [5]テーブル、チャート、コード表示プラグインを活用する - みてわかる!jQuery入門:ITpro
- Comparing HTML5 Mobile Web Framework - Dzyngiri
- 20 More CSS3 Tutorials and Techniques for Creating Buttons
- Infragistics jQuery Controls – Impressive & Professional jQuery Toolset
- remybach/jQuery.superLabels - GitHub
- Tips and best practices to develop responsive websites | CatsWhoCode.com
- What’s new for designers, May 2012 | Webdesigner Depot
- dynamo.js
- 21 Fantastic Examples of Sliders in Web Design | Inspiration
- Edit this Fiddle - jsFiddle
A jQuery UI Combobox: Under the hood
Update on 2010-08-17: This article was updated to reflect the changes to the combobox code in jQuery UI 1.8.4
The jQuery UI 1.8 release brings along the new autocomplete widget. An autocomplete adds a list of suggestions to an input field, displayed and filtered while the user is typing. This could be attached to a search field, suggesting either search terms or just matching results for faster navigation. But what if there is a fixed list of options, usually implemented as a standard HTML select element, where the ability to filter would help users find the right value way faster?
That’s a “combobox.” A combobox works like a select, but also has an input field to filter the options by typing. jQuery UI 1.8 actually provides a sample implementation of a combobox as a demo. In this article, we’ll look under the hood of the combobox demo, to explore both the combobox widget and the autocomplete widget that it uses.
Let’s starts with the initial markup:
-
<label>Your preferred programming language: </label>
-
<select>
-
<option value="a">asp</option>
-
<option value="c">c</option>
-
<option value="cpp">c++</option>
-
<option value="cf">coldfusion</option>
-
<option value="g">groovy</option>
-
<option value="h">haskell</option>
-
<option value="j">java</option>
-
<option value="js">javascript</option>
-
<option value="p1">perl</option>
-
<option value="p2">php</option>
-
<option value="p3">python</option>
-
<option value="r">ruby</option>
-
<option value="s">scala</option>
-
</select>
Nothing special there, just a label and a select element with a few options.
The code to apply the combobox widget to the select is quite simple, too:
-
$("select").combobox();
Let’s look at the code for this combobox widget. First, the full code, to give you an overview. We’ll dig into the details step-by-step afterwards.
-
$.widget( "ui.combobox", {
-
_create: function() {
-
var self = this;
-
var input = $( "<input />" )
-
.autocomplete({
-
delay: 0,
-
minLength: 0,
-
source: function(request, response) {
-
var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
-
return {
-
new RegExp(
-
"(?![^&;]+;)(?!<[^<>]*)(" +
-
$.ui.autocomplete.escapeRegex(request.term) +
-
")(?![^<>]*>)(?![^&;]+;)", "gi"),
-
"<strong>$1</strong>"),
-
option: this
-
};
-
}) );
-
},
-
ui.item.option.selected = true;
-
self._trigger( "selected", event, {
-
item: ui.item.option
-
});
-
},
-
if ( !ui.item ) {
-
valid = false;
-
if ( this.value.match( matcher ) ) {
-
this.selected = valid = true;
-
return false;
-
}
-
});
-
if ( !valid ) {
-
// remove invalid value, as it didn’t match anything
-
return false;
-
}
-
}
-
}
-
})
-
-
return $( "<li></li>" )
-
};
-
-
$( "<button> </button>" )
-
.button({
-
icons: {
-
primary: "ui-icon-triangle-1-s"
-
},
-
})
-
// close if already visible
-
if (input.autocomplete("widget").is(":visible")) {
-
input.autocomplete("close");
-
return;
-
}
-
// pass empty string as value to search for, displaying all results
-
input.autocomplete("search", "");
-
input.focus();
-
});
-
}
-
});
Let’s break this down, piece by piece:
-
$.widget( "ui.combobox", {
-
_create: function() {
-
// all the code
-
}
-
});
This defines a new widget, in the ui namespace (don’t use this for your own widgets, it’s reserved for jQuery UI widgets) and adds the only method, _create. This is the constructor method for jQuery UI widgets, and will be called only once. In versions prior to 1.8 it was called _init. The _init method still exists, but it is called each time you call .combobox() (with or without options). Keep in mind that our widget implementation is not complete, as it lacks the destroy method. It’s just a demo.
Coming up next is the creation of an input element and applying the autocomplete to it, with data provided by the select element.
-
var self = this;
-
var input = $("<input />")
-
.autocomplete({
-
delay: 0,
-
minLength: 0
-
source: function(request, response) {
-
// implements retrieving and filtering data from the select
-
},
-
// implements first part of updating the select with the selection
-
},
-
// implements second part of updating the select with the selection
-
},
-
})
It starts with a few variable declarations: var self = this will be used inside callbacks below, where this will refer to something else. The var select references the select element on which the combobox gets applied. To replace the select with the text input, the select is hidden.
The selected and value variables are used to initialized the autocomplete with the current value of the select.
An input element is created from scratch, inserted after the select element into the DOM, and transformed into an autocomplete widget. All three autocomplete options are customized:
- delay specifies the amount of time to wait for displaying data between each key press, here set to zero as the data is local
- minLength is set to 0, too, so that a cursor-down or -up key press will display the autocomplete menu, even when nothing was entered.
- source provides the filtered data to display
Let’s break down the source implementation:
-
source: function(request, response) {
-
var matcher = new RegExp( $.ui.autocomplete.escapeRegex(request.term), "i" );
-
return {
-
new RegExp(
-
"(?![^&;]+;)(?!<[^<>]*)(" +
-
$.ui.autocomplete.escapeRegex(request.term) +
-
")(?![^<>]*>)(?![^&;]+;)", "gi"),
-
"<strong>$1</strong>"),
-
option: this
-
};
-
}) );
-
},
There is a bit of matching and mapping involved here: At first, a regular expression object is defined, based on the entered term, escaped with the help of the $.ui.autocomplte.escapeRegex utility method. This regex gets reused in the function below. The response argument, a callback, gets called, to provide the data to display. The argument passed is the result of the call to select.find("option").map(callback). That finds all option elements within our original select, then maps each option to a different object, implemented in another callback passed to the map method.
This callback will return undefined, thereby removing an item, when a search term is present and the text of the option doesn’t match the entered value. Otherwise (no term, or it matches), it’ll return an object with three properties:
- label: based on the text of the option, with the matched term highlighted with some regexing (another example of a write-only regular expression)
- value: the unmodified text of the option, to be inserted into the text input field
- option: the option element itself, to update the select (via the selected-property) or to pass on in custom events
The label and value properties are expected by the autocomplete widget, the option property has an arbitrary name, used here only by the combobox widget.
Before, I mentioned that the combobox widget customizes all three autocomplete options, but there were actually five options specified. The fourth and fifth properties, select and change, are event. This is the select implementation:
-
ui.item.option.selected = true;
-
self._trigger( "selected", event, {
-
item: ui.item.option
-
});
-
},
The ui.item argument refers to the data we provided in the source option. Via the ui.item.option property we can update the underlying select to the selected item, as well as triggering a selected events for further customization of the combobox widget.
To cover the case where no selection is made, the change event is used:
-
if ( !ui.item ) {
-
valid = false;
-
if ( this.value.match( matcher ) ) {
-
this.selected = valid = true;
-
return false;
-
}
-
});
-
if ( !valid ) {
-
// remove invalid value, as it didn’t match anything
-
return false;
-
}
-
}
-
},
Here the entered value is used to try and match a selection. If the value doesn’t match anything, it’ll get removed, and the underlying select is set to an empty value, too.
The next block customizes the _renderItem method of the underlying autocomplete. This is necessary to output the highlighting on each row, as autocomplete by default will escape any html.
And finally, the last block creates the button that opens the full list of options:
-
$( "<button> </button>" )
-
.button({
-
icons: {
-
primary: "ui-icon-triangle-1-s"
-
},
-
})
-
// close if already visible
-
if (input.autocomplete("widget").is(":visible")) {
-
input.autocomplete("close");
-
return;
-
}
-
// pass empty string as value to search for, displaying all results
-
input.autocomplete("search", "");
-
input.focus();
-
});
Another element is created on-the-fly. It gets tabIndex="-1" to take it out of the tab order, as it’s mostly useful for mouse interactions. Keyboard interaction is already covered by the input element. It gets a title attribute to provide a tooltip and is inserted after the input element into the DOM. A call to .button() with some options together with a bit of class-mangling transforms the button into a Button widget that displays a down-arrow icon with rounded corners on the right (the input has rounded-corners on the left).
Finally a click event is bound to the button: If the autocomplete menu is already visible, it gets closed, otherwise the autocomplete’s search method is called with an empty string as the argument, to search for all elements, independent of the current value within the input. As the input handles keyboard input, it gets focused. Having focus on the button would be useless or would require duplicate keyboard interaction that the input already supports.
And that’s it! We can see that the autocomplete widget is flexible enough to allow all this with option customization, events, and calling a few methods. We don’t have to “subclass” autocomplete (creating a new widget with the autocomplete as the parent prototype instead of $.widget). Instead, we can make the combobox mostly independent of any internal or private autocomplete methods. For the full experience and latest version, check out the combobox demo on the jQuery UI site.
Read the full/original article at Learning jQuery
Comments are closed.
Learn more about jQuery
I only just found out that the jQuery validation plugins has a validation rule called “remote” which can be used ...
jQuery function to check if horizontal scroll is present – hasHScrollBar() – (or vertical check below also, util function to ...
jQuery function to Set any DOM Element to Top View (bring to front) using CSS Z-Index property.
Is it possible to declare arrays in JavaScript object literal notation? Example 1 – this works with arrays Declaration: Storage ...
To get the a variables type using jQuery there is a jQuery function called .type() which returns “array”, “string”, “number”, ...
In this post you can find tutorials which explain step by step different API use cases with jQuery like Google ...
For valuable work on creation of sites you need a good comfortable editor necessarily. There are many requiring paid products ...
Today we are sharing with you a collection of awesome jQuery Camera Photo plugins. They offer a range of image ...
Back in the day, if you saw something that was animated on a website it was automatically assumed to be ...
In this post, we have compiled a list of 10 jQuery HTML5 Audio players available today, most allow native audio ...
jQuery Mobile is a powerful framework for making mobile web applications. But can we use it to convert existing desktop ...
I have jotted a quick post on a Basic JavaScript Regular Expression Example to give beginners out there a taste ...
In April 2012′s edition of Interestingly Random JavaScript, jQuery and Web Development we bring you some very cool stuff such ...
In this post we are sharing you a roundup of 10 really jQuery plugins as of today. Pretty cool plugins ...
As always expected from the jQuery community, the compilation we have for you today are some good and impressive recently ...
A collection of jQuery PNG/JPEG/GIF plugins that enables image animation, cartoon-like background, etc… let them help you design displays for ...
A collection of JavaScript/jQuery Zip/File/Compressor plugins that allows you to minify your JS code and compress your JS files ready ...
Quick jQuery code snippet on how to keep an element in view. For demo scroll down on any page on ...
Here is what I think is the best and most reliable way to load jQuery library and jQuery UI Libraries. ...
jQuery code snippet which outputs all attributes of element using the default .attr() function on any dom element(s). usage: output:
Use jQuery and the Google Maps API to create your own map application.
Super cool and easy way to get stylish tooltips with jQuery.
The right way to include the jQuery library in WordPress.
