Class glow.ui.AutoSuggest
Extends
glow.ui.Widget.
Defined in: ui.js.
| Constructor Attributes | Constructor Name and Description |
|---|---|
|
glow.ui.AutoSuggest(opts)
Create a menu that displays results filtered by a search term.
|
| Field Attributes | Field Name and Description |
|---|---|
|
The options object passed into #bindInput, with defaults added.
|
|
|
The focusable linked to this autosuggest.
|
|
|
Refers to the input element to which this is linked to, or an empty NodeList.
|
|
|
The overlay linked to this autosuggest.
|
- Fields borrowed from class glow.ui.Widget:
- container, content, phase
| Method Attributes | Method Name and Description |
|---|---|
|
bindInput(input, opts)
Link this autosuggest to a text input.
|
|
|
data(data)
Set the data or datasource to search.
|
|
|
destroy()
Destroy the AutoSuggest.
|
|
|
disabled(newState)
Enable/disable the AutoSuggest, or get the disabled state
When the AutoSuggest is disabled it is not shown.
|
|
|
find(str)
Search the datasource for a given string
This fetches results from the datasource and displays them.
|
|
|
hide()
Clear the results so the AutoSuggest is no longer visible
|
|
|
setFilter(filter)
Set the function used to filter the dataset for results.
|
|
|
setFormat(formatter)
Control how matches are output.
|
- Methods borrowed from class glow.events.Target:
- detach, fire, on
| Event Attributes | Event Name and Description |
|---|---|
|
data(event)
Fired when the dataset changes
This can be the result of calling {@link glow.ui.AutoSuggest#data data} or
new data has been fetched from the server.
|
|
|
find(event)
Fired when a search starts.
|
|
|
results(event)
Fired when the dataset has been filtered but before HTML is output
You can use this event to sort the dataset and/or add additional items
Cancelling this event is equivalent to setting event.results to an
empty array.
|
|
|
select(event)
Fired when an item in the AutoSuggest is selected.
|
- Events borrowed from class glow.ui.Widget:
- destroy, disable
Class Detail
glow.ui.AutoSuggest(opts)
Create a menu that displays results filtered by a search term.
This widget can be easily linked to a text input via glow.ui.AutoSuggest#linkToInput
so results will be filtered by text entered by the user. This appears as a list of selectable
items below the input element (optional) which dynamically updates based on what
has been typed so far.
By default, items where the search term matches the start of the item
(or its 'name' property) will be returned. You can change the
filtering behaviour via {@link glow.ui.AutoSuggest#setFilter setFilter}.
The matched item (or its 'name' property) will be displayed with the matching
portion underlined. You can change the output via {@link glow.ui.AutoSuggest#setFormat setFormat}
// Make an input auto-complete from an array of tags for a recipe database
glow.ui.AutoSuggest()
.data(['Vegetarian', 'Soup', 'Sandwich', 'Wheat-free', 'Organic', 'etc etc'])
.linkToInput('#recipeTags');
// An AutoSuggest embedded in the page, rather than in an overlay
var myAutoSuggest = glow.ui.AutoSuggest()
.data('recipe.php?ingredients={val}')
.linkToInput('#username', {
// don't use an overlay, we'll add the autosuggest to the document outselves
useOverlay: false
});
// add the results into the document
myAutoSuggest.container.appendTo('#results');
// Make an input suggest from an array of program names, where the
// whole string is searched rather than just the start
// When the item is clicked, we go to a url
new glow.ui.AutoSuggest().setFilter(function(item, val) {
return item.name.indexOf(val) !== -1;
}).data([
{name: 'Doctor Who', url: '...'},
{name: 'Eastenders', url: '...'},
{name: 'The Thick Of It', url: '...'},
// ...
]).linkToInput('#programSearch').on('select', function(event) {
location.href = event.selected.url;
});
- Parameters:
- {Object} opts Optional
- Options
- {number} opts.width Optional
- Apply a width to the results list. By default, the AutoSuggest is the full width of its containing element, or the width of the input it's linked to if autoPositioning.
- {number} opts.maxResults Optional
- Limit the number of results to display.
- {number} opts.minLength Optional, Default: 3
- Minimum number of chars before search is executed This prevents searching being performed until a specified amount of chars have been entered.
- {boolean} opts.caseSensitive Optional, Default: false
- Whether case is important when matching suggestions. If false, the value passed to the filter will be made lowercase, a custom filter must also lowercase the property it checks.
- {boolean} opts.activateFirst Optional, Default: true
- Activate the first item when results appear? If false, results with be shown with no active item.
- {function|string} opts.keyboardNav Optional, Default: 'arrow-y'
- Alter the default keyboard behaviour. This is the same as keyboardNav in glow.ui.Focusable.
Field Detail
{Object}
bindOpts
The options object passed into #bindInput, with defaults added.
{glow.ui.Focusable}
focusable
The focusable linked to this autosuggest.
{glow.NodeList}
input
Refers to the input element to which this is linked to, or an empty NodeList.
Link an input to an AutoSuggest using {@link glow.ui.AutoSuggest#bindInput bindInput}.
{glow.ui.Overlay}
overlay
The overlay linked to this autosuggest.
The Overlay is created when {@link glow.ui.AutoSuggest#bindInput bindInput} is
called.
Method Detail
bindInput(input, opts)
Link this autosuggest to a text input.
This triggers glow.ui.AutoSuggest#find when the value in
the input changes.
The AutoSuggest is placed in an Overlay beneath the input and displayed
when results are found.
If the input loses focus, or esc is pressed,
the Overlay will be hidden and results cleared.
- Parameters:
- {selector|glow.NodeList|HTMLElement} input
- Test input element
- {Object} opts Optional
- Options
- {selector|glow.NodeList} opts.appendTo Optional
- Add the AutoSuggest somewhere in the document rather than an {@link glow.ui.Overlay Overlay} By default, the AutoSuggest will be wrapped in an {@link glow.ui.Overlay Overlay} and appended to the document's body.
- {boolean} opts.autoPosition Optional, Default: true
- Place the overlay beneath the input If false, you need to position the overlay's container manually. It's recommended to do this as part of the Overlay's show event, so the position is updated each time it appears.
- {boolean} opts.autoComplete Optional, Default: true
- Update the input when an item is highlighted & selected. This will complete the typed text with the result matched. You can create custom actions by listening for the {@link glow.ui.AutoSuggest#event:select 'select' event}
- {string} opts.delim Optional
- Delimiting char(s) for selections. When defined, the input text will be treated as multiple values, separated by this string (with surrounding spaces ignored).
- {number} opts.delay Optional, Default: 0.5
- How many seconds to delay before searching. This prevents searches being made on each key press, instead it waits for the input to be idle for a given number of seconds.
- {string} opts.anim Optional
- Animate the Overlay when it shows/hides. This can be any parameter accepted by {@link glow.ui.Overlay#setAnim Overlay#setAnim}.
- {string} opts.loadingClass Optional
- Class name added to the input while data is being loaded. This can be used to change the display of the input element while data is being fetched from the server. By default, a spinner is displayed in the input.
- Returns:
- this
data(data)
Set the data or datasource to search.
This gives the AutoSuggest the data to search, or the means to fetch
the data to search.
// providing a URL
myAutoSuggest.data('/search?text={val}');
// providing an array of program names myAutoSuggest.data( ['Doctor Who', 'Eastenders', 'The Thick of it', 'etc etc'] );
// providing an object of user data
myAutoSuggest.data([
{name='JaffaTheCake', fullName:'Jake Archibald', photo:'JaffaTheCake.jpg'},
{name='Bobby', fullName:'Robert Cackpeas', photo:'Bobby.jpg'}
...
]);
// Getting the data via jsonp
var request;
myAutoSuggest.data(function(val, callback) {
// abort previous request
request && request.abort();
request = glow.net.getJsonp('http://blah.com/data?callback={callback}&val=' + val)
.on('load', function(data) {
callback(data);
})
});
- Parameters:
- {string|string[]|Object[]|glow.net.Response|function} data
- Data or datasource.
String URL
A URL on the same domain can be provided, eg 'results.json?search={val}', where {val} is replaced with the search term. If {val} is used, the URL if fetched on each search, otherwise it is only fetched once on the first search. The result is a glow.net.XhrResponse, by default this is decoded as json. Use the 'data' event to convert your incoming data from other types (such as XML).glow.net.XhrResponse
This will be treated as a json response and decoded to string[] or Object[], see below.string[] or Object[] dataset
An Array of strings can be provided. Each string will be converted to {name: theString}, leaving you with an array of objects. An Array of objects can be provided, each object is an object that can be matched. By default the 'name' property of these objects is searched to determine a match, but {@link glow.ui.AutoSuggest#filter filter} can be used to change this.function
Providing a function means you have total freedom over fetching the data for your autoSuggest, sync or async. Your function will be called by the AutoSuggest whenever a {@link glow.ui.AutoSuggest#find find} is performed, and will be passed 2 arguments: the search string and a callback. You can fetch the data however you wish. Once you have the data, pass it to the callback to complete the {@link glow.ui.AutoSuggest#find find}. Until the callback is called, the AutoSuggest remains in a 'loading' state. `this` inside the function refers to the AutoSuggest instance. Your function will be called multiple times, ensure you cancel any existing requests before starting a new one.
- Returns:
- this
destroy()
Destroy the AutoSuggest.
Removes all events that cause the AutoSuggest to run. The input
element will remain on the page.
{glow.ui.AutoSuggest|boolean}
disabled(newState)
Enable/disable the AutoSuggest, or get the disabled state
When the AutoSuggest is disabled it is not shown.
- Parameters:
- {boolean} newState Optional
- Disable the AutoSuggest? 'false' will enable a disabled AutoSuggest.
- Returns:
- {glow.ui.AutoSuggest|boolean} Returns boolean when getting, AutoSuggest when setting
find(str)
Search the datasource for a given string
This fetches results from the datasource and displays them. This
may be an asyncrounous action if data needs to be fetched from
the server.
- Parameters:
- {string} str
- String to search for {@link glow.ui.AutoSuggest#filter AutoSuggest#filter} is used to determine whether results match or not.
- Returns:
- this
hide()
Clear the results so the AutoSuggest is no longer visible
- Returns:
- this
setFilter(filter)
Set the function used to filter the dataset for results.
Overwrite this to change the filtering behaviour.
// Search the name property for strings that contain val
myAutoSuggest.setFilter(function(val, caseSensitive) {
var name = caseSensitive ? this.name : this.name.toLowerCase();
return name.indexOf(val) !== -1;
});
// Search the tags property for strings that contain val surrounded by pipe chars
// this.tags is like: |hello|world|foo|bar|
myAutoSuggest.setFilter(function(val, caseSensitive) {
var tags = caseSensitive ? this.tags : this.tags.toLowerCase();
return tags.indexOf('|' + val + '|') !== -1;
});
- Parameters:
- {function} filter
- Filter function. Your function will be passed 2 arguments, the term entered by the user, and if the search should be case sensitive. Return true to confirm a match. 'this' will be the item in the dataset to check. If the search is case-insensitive, the term entered by the user is automatically lowercased. The default filter will return items where the search term matches the start of their 'name' property. If the dataset is simply an array of strings, that string will be used instead of the 'name' property.
- Returns:
- this
setFormat(formatter)
Control how matches are output.
// A username auto-complete
// The data url returns a JSON object like [{name='JaffaTheCake', fullName:'Jake Archibald', photo:'JaffaTheCake.jpg'}, ...]
glow.ui.AutoSuggest().setFormat(function() {
// Format the results like
Jake Archibald (JaffaTheCake)
return '
' + data.fullName + ' (' + data.name + ')';
}).data('userSearch.php?usernamePartial={val}').linkToInput('#username');
- Parameters:
- {function} formatter
- Function to generate output. The first param to your function will be the matched item from your data list. The second param is the search value. Return an HTML string or glow.NodeList to display this item in the results list. Ensure you escape any content you don't want treated as HTML.
- Returns:
- this
Event Detail
data(event)
Fired when the dataset changes
This can be the result of calling {@link glow.ui.AutoSuggest#data data} or
new data has been fetched from the server.
You can use this event to intercept and transform data into the
correct JSON format.
Cancel this event to ignore the new dataset, and continue
with the current one.
myAutoSuggest.data('data.xml?search={val}').on('data', function(event) {
// When providing a url to .data(), event.data is a glow.net.XhrResponse object
// Note: xmlToJson is not a function defined by Glow
event.data = xmlToJson( event.data.xml() );
});
- Parameters:
- {glow.events.Event} event
- Event Object
- {*} event.data
- The new dataset You can modify / overwrite this property to alter the dataset. The type of this object depends on the data source and other listeners which may have overwritten / changed the original data.
find(event)
Fired when a search starts.
Cancel this event to prevent the search.
- Parameters:
- {glow.events.Event} event
- Event Object.
- {string} event.val
- The search string. You can set this to another value if you wish.
results(event)
Fired when the dataset has been filtered but before HTML is output
You can use this event to sort the dataset and/or add additional items
Cancelling this event is equivalent to setting event.results to an
empty array.
myAutoSuggest.on('results', function(event) {
// sort results by an 'author' property
event.results = event.results.sort(function(a, b) {
return a.author > b.author ? 1 : -1;
});
// Add a 'More...' item to the data set
event.results.push( {name:'More...'} );
// Behaviour will be added into the 'select' listener to handle what
// happens when 'More...' is selected
});
- Parameters:
- {glow.events.Event} event
- Event Object
- {string[]|Object[]} event.results
- The filtered dataset You can modify / overwrite this property to alter the results
select(event)
Fired when an item in the AutoSuggest is selected.
You can use this event to react to the user interacting with
the AutoSuggest
Cancel this event to prevent the default click action.
myAutoSuggest.on('select', function(event) {
// this assumes our data objects have a 'url' property
loaction.href = event.item.url;
});
- Parameters:
- {glow.events.Event} event
- Event Object
- {string|Object} event.item
- The item in the dataset that was selected
- {glow.NodeList} event.li
- The list item in the AutoSuggest that was selected