You might want to read the Security Section about possible XSS vulnerabilities
Types
Standard
A search can display a set of results
Category
A search can display results from remote content ordered by categories
Horizontal Category
You can also display horizontal category names on top of each results instead.
Local Search
A search can look for results inside a static local source.
Local Category Search
A search can look for category results inside a static local source.
Search ignoring Diacritics
A selection dropdown can allow a user to ignore all Diacritics while searching.
States
Loading
A search can show a loading indicator
Variations
Disabled
A search can show it is currently unable to be interacted with
Scrolling
A search can have its results scroll.
Height
A search can be very short (0.75x of default height) so that more results can be glanced.
Long: 2x of default height
Fluid
A search can have its results take up the width of its container
Aligned
A search can have its results aligned to its left or right container edge
Size
A search can vary in size
Initializing
Automatic Routing
By default search will automatically route to the named API endpoint 'search'
Named URL
You can specify custom API settings to adjust the url, callback settings, or specify a different API action.
Local Object
Local search results allow you to search across specified properties of a javascript object literal looking for matching values
You can set which fields are searchable using the searchFields
setting.
Server Responses
Standard
Category
Retrieving Results
Unique IDs
If no id
property is included on a result, a key will automatically be generated when your results are returned for each result.
IDs are generated using the position in the results, for example the first element will receive the id 1
, and the first category result will receive the id a1
.
An id
or search result title can then be used with get result(value)
to return the result object.
Behaviors
All the following behaviors can be called using the syntax:
Behavior | Description |
---|---|
query (callback) | Search for value currently set in search input |
display message(text, type) | Displays message in search results with text, using template matching type |
cancel query | Cancels current remote search query |
search local(query) | Search local object for specified query and display results |
has minimum characters | Whether has minimum characters |
search remote(query, callback) | Search remote endpoint for specified query and display results |
search object(query, object, searchFields) | Search object for specified query and return results |
is focused | Whether search is currently focused |
is visible | Whether search results are visible |
is empty | Whether search results are empty |
get value | Returns current search value |
get result(value) | Returns JSON object matching searched title or id (see above) |
set value(value) | Sets search input to value |
read cache(query) | Reads cached results for query |
clear cache(query) | Clears value from cache, if no parameter passed clears all cache |
write cache(query) | Writes cached results for query |
add results(html) | Adds HTML to results and displays |
show results(callback) | Shows results container |
hide results(callback) | Hides results container |
generate results(response) | Generates results using parser specified by settings.template |
destroy | Removes all events |
Examples
Using Different Response Fields
Search expects a very specific API response, however you can easily modify the mapping of server response to displayed field using the fields
parameter.
Using API Settings
API provides a callback onResponse
that can be used to restructure third party APIs to match the expected server response for search.
You can also use mockResponseAsync
to use a custom backend for fulfilling searches.
Search
Behavior
Default | Description | |
---|---|---|
apiSettings |
{
action: 'search'
}
|
Settings for API call. |
minCharacters | 1 | Minimum characters to query for results |
searchOnFocus | true | Whether search should show results on focus (must also match min character length) |
transition | scale | Named transition to use when animating menu in and out. Fade and slide down are available without including ui transitions |
duration | 200 | Duration of animation events |
maxResults | 7 | Maximum results to display when using local and simple search, maximum category count for category search |
cache | true | Caches results locally to avoid requerying server |
source | false | Specify a Javascript object which will be searched locally |
selectFirstResult | false | Whether the search should automatically select the first search result after searching |
preserveHTML | true | Whether to preserve possible html of resultset values |
showNoResults | true | Whether a "no results" message should be shown if no results are found. (These messages can be modified using the template object specified below) |
fullTextSearch | 'exact' |
Possible values
searchFullText .)
|
fields |
fields: {
categories : 'results', // array of categories (category view)
categoryName : 'name', // name of category (category view)
categoryResults : 'results', // array of results (category view)
description : 'description', // result description
image : 'image', // result image
price : 'price', // result price
results : 'results', // array of results (standard)
title : 'title', // result title
url : 'url', // result url
action : 'action', // "view more" object name
actionText : 'text', // "view more" text
actionURL : 'url' // "view more" url (if set to false the text will appear as a div)
}
|
List mapping display content to JSON property, either with API or source . |
searchFields |
[
'id',
'title',
'description'
]
|
Specify object properties inside local source object which will be searched |
hideDelay | 0 | Delay before hiding results after search blur |
searchDelay | 200 | Delay before querying results on inputchange |
easing | easeOutExpo | Easing equation when using fallback Javascript animation. EaseOutExpo is included with search, for additional options you must include easing equations |
ignoreDiacritics | false | When activated, searches will also match results for base diacritic letters. For example when searching for 'a', it will also match 'á' or 'â' or 'å' and so on...
It will also ignore diacritics for the searchterm, so if searching for 'ó', it will match 'ó', but also 'o', 'ô' or 'õ' and so on... Not available in IE |
type | 'standard' | Template to use (specified in settings.templates) |
displayField | '' | Field to display in standard results template |
automatic | true | Whether to add events to prompt automatically |
Callbacks
Context | Description | |
---|---|---|
onSelect(result, response) | module | Callback on element selection by user. The first parameter includes the filtered response results for that element. The function should return false to prevent default action (closing search results and selecting value). |
onResultsAdd(html) | module | Callback after processing element template to add HTML to results. Function should return false to prevent default actions. |
onSearchQuery(query) | module | Callback on search query |
onResults(response, fromCache) | module | Callback on server response. If the results were generated from cache, the fromCache parameter is true |
onResultsOpen | results element | Callback when results are opened |
onResultsClose | results element | Callback when results are closed |
Templates
These templates are used to generate the HTML structures for search results
Functions | |
---|---|
templates |
$.fn.search.settings.templates : {
escape: function(string) {
// returns escaped string for injected results
},
message: function(message, type) {
// returns html for message with given message and type
},
category: function(response) {
// returns results html for category results
},
standard: function(response) {
// returns results html for standard results
}
}
|
Module
These settings are native to all modules, and define how the component ties content to DOM attributes, and debugging settings for the module.
Default | Description | |
---|---|---|
name | Search | Name used in log statements |
namespace | search | Event namespace. Makes sure module teardown does not effect other events attached to an element. |
regExp |
regExp: {
escape : /[\-\[\]\/\{\}\(\)\*\+\?\.\\\^\$\|]/g,
beginsWith : '(?:\s|^)'
}
|
Regular expressions used for matching |
selector |
selector : {
prompt : '.prompt',
searchButton : '.search.button',
results : '.results',
message : '.results > .message',
category : '.category',
result : '.result',
title : '.title, .name'
}
|
Selectors used to find parts of a module |
metadata |
metadata: {
cache : 'cache',
results : 'results',
result : 'result'
}
|
HTML5 metadata attributes used internally |
className |
className: {
animating : 'animating',
active : 'active',
category : 'category',
empty : 'empty',
focus : 'focus',
hidden : 'hidden',
loading : 'loading',
results : 'results',
pressed : 'down'
}
|
Class names used to determine element state |
silent | false | Silences all console output including error messages, regardless of other debug settings. |
debug | false | Debug output to console |
performance | true | Show console.table output with performance metrics |
verbose | false | Debug output includes all internal behaviors |
error |
error : {
source : 'Cannot search. No source used, and Semantic API module was not included',
noResultsHeader : 'No Results',
noResults : 'Your search returned no results',
noTemplate : 'A valid template name was not specified.',
oldSearchSyntax : 'searchFullText setting has been renamed fullTextSearch for consistency, please adjust your settings.',
serverError : 'There was an issue with querying the server.',
maxResults : 'Results must be an array to use maxResults setting',
method : 'The method you called is not defined.',
noNormalize : '"ignoreDiacritics" setting will be ignored. Browser does not support String().normalize(). You may consider including
|
Taking care of untrusted remote data
Untrusted Data
You should never trust any data and should make sure all data is processed on the server to sanitize before passing it to the client.
However you might want to use existing foreign API services as data storage in your search module. In this case it is recommended to set the preserveHTML
option to false
. Then all data provided by the frontend will be either encoded to use HTML-entities for the most evil characters like &, <, >, ", ', `
or any html data will be completely removed on item selection
Evil API Example
The following search fields are bound to an evil API backend which tries to inject code