Menu

Search
A search module allows a user to query for results from a selection of data

Types

Standard

A search can display a set of results

Using a ui input allows you to use additional input types, like this icon input

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.

By default, results will return content first that begin with the query text, but also afterward content that matches the query anywhere inside. To disable full text search you can specify in settings fullTextSearch: false.
$('.ui.search') .search({ source: content }) ;

Local Category Search

A search can look for category results inside a static local source.

By default, results will return content first that begin with the query text, but also afterward content that matches the query anywhere inside. To disable full text search you can specify in settings fullTextSearch: false.
$('.ui.search') .search({ type: 'category', source: categoryContent }) ;

Search ignoring Diacritics

A selection dropdown can allow a user to ignore all Diacritics while searching.

If you want to support IE using the ignoreDiacritics option, you have to include a polyfill for the String().normalize() method like unorm.
$('#diacriticsexample') .search({ ignoreDiacritics: true, fullTextSearch:'exact', source: [ { title: 'André'}, { title: 'Bokmål'}, { title: 'café'}, { title: 'cafetería'}, { title: 'château'}, { title: 'décolleté'}, { title: 'Élysée'}, { title: 'Fräulein'}, { title: 'garçon'}, { title: 'háček'}, { title: 'inrō'}, { title: 'jūjutsu'}, { title: 'kroužek'}, { title: 'La Niña'}, { title: 'Māori'}, { title: 'négligée'}, { title: 'pączki'}, { title: 'Québec'}, { title: 'ragoût'}, { title: 'Škoda'}, { title: 'takahē'}, { title: 'über'}, { title: 'voilà'}, { title: 'whekī'}, { title: 'c Zoë'} ] }) ;

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.

The search scroll height depends on viewport size. The search scroll height is calculated using search item height * number of items to be shown for applicable media query break point.

You can also use resizable scrolling and a native resize drag handler will appear to the bottom right of the results. This needs a modern browser, so does not work in IE11 or legacy Edge.

Height

A search can be very short (0.75x of default height) so that more results can be glanced.

The default height is calculated using search item height * number of items to be shown for applicable media query break point.

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

Search is built ontop of Semantic API behaviors to allow for URL templating, and UI state management. Please check out the API documentation for more information on adjusting API settings.

Automatic Routing

By default search will automatically route to the named API endpoint 'search'

// initializes with default endpoint /search/{query} $('.ui.search') .search({ type: 'category' }) ;

Named URL

You can specify custom API settings to adjust the url, callback settings, or specify a different API action.

$('.ui.search') .search({ // change search endpoint to a custom endpoint by manipulating apiSettings apiSettings: { url: 'custom-search/?q={query}' }, type: 'category' }) ;

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.

// searches across any array/object of searchable objects var content = [ { title: 'Horse', description: 'An Animal', }, { title: 'Cow', description: 'Another Animal', } ] ; $('.ui.search') .search({ source : content, searchFields : [ 'title' ], fullTextSearch: false }) ;

Server Responses

You may also consider adding a top level property like success: true and using API's successTest parameter to determine whether a server response is actually successful, even if it returns the correct HTTP code

Standard

{ "results": [ { "title": "Result Title", "url": "/optional/url/on/click", "image": "optional-image.jpg", "price": "Optional Price", "description": "Optional Description" }, { "title": "Result Title", "description": "Result Description" } ], // optional action below results "action": { "url": '/path/to/results', "text": "View all 202 results" } }

Category

{ "results": { "category1": { "name": "Category 1", "results": [ { "title": "Result Title", "url": "/optional/url/on/click", "image": "optional-image.jpg", "price": "Optional Price", "description": "Optional Description" }, { "title": "Result Title", "url": "/optional/url/on/click", "image": "optional-image.jpg", "price": "Optional Price", "description": "Optional Description" } ] }, "category2": { "name": "Category 2", "results": [ { "title": "Result Title", "url": "/optional/url/on/click", "image": "optional-image.jpg", "price": "Optional Price", "description": "Optional Description" } ] } }, // optional action below results "action": { "url": '/path/to/results', "text": "View all 202 results" } }

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.

// get result from current query results with the title cat $('.ui.search') .search('get result', 'cat') ; // get first result from first category with category search $('.ui.search') .search('get result', 'a1') ; // get first result from standard search $('.ui.search') .search('get result', '1') ;

Behaviors

All the following behaviors can be called using the syntax:

$('.your.element') .search('behavior name', argumentOne, argumentTwo) ;
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.

$('.ui.search') .search({ apiSettings: { url: 'https://api.github.com/search/repositories?q={query}' }, fields: { results : 'items', title : 'name', url : 'html_url' }, minCharacters : 3 }) ;

Using API Settings

Be careful when working with foreign remote API services

You might want to read the Security Section about possible XSS vulnerabilities

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.

$('.ui.search') .search({ type : 'category', minCharacters : 3, apiSettings : { onResponse: function(githubResponse) { var response = { results : {} } ; // translate GitHub API response to work with search $.each(githubResponse.items, function(index, item) { var language = item.language || 'Unknown', maxResults = 8 ; if(index >= maxResults) { return false; } // create new language category if(response.results[language] === undefined) { response.results[language] = { name : language, results : [] }; } // add result to category response.results[language].results.push({ title : item.name, description : item.description, url : item.html_url }); }); return response; }, url: 'https://api.github.com/search/repositories?q={query}' } }) ;

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
  • 'exact' will force the exact search to be matched somewhere in the string
  • 'some' Will do the same as exact but supports multiple search values separated by whitespace. At least one word must match
  • 'all' is same as some but all words have to match in all given searchfields of each record altogether
  • true will use a fuzzy full text search
  • false will only match to start of string.
(This setting was previously called 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

By specifying a search as type: 'customType', and a custom template under $.fn.search.settings.templates.customType you can create custom search results. Keep in mind that .title will be used for matching results onSelect
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 as a polyfill.' },

Taking care of untrusted remote data

No responsibility
  • Fomantic has some basic features included to prevent XSS when working with remoteData.
  • There is no guarantee and fomantic does not promise, that your site will not be vulnerable against data of any unknown remote data source
  • Fomantic-UI is not responsible for how you process and use data and by using fomantic you agree that you are reliable for any damage or charges placed against you (or your company) for any issues caused by data processing
HINT

Look at https://www.owasp.org/index.php/XSS_(Cross_Site_Scripting)_Prevention_Cheat_Sheet to find out more and to learn what you should be aware of

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

$('.ui.search') .search({ preserveHTML : false, apiSettings: { url: 'https://api.github.com/search/repositories?q={query}' }, fields: { results : 'items', title : 'name', url : 'html_url' }, minCharacters : 3 });

Evil API Example

The following search fields are bound to an evil API backend which tries to inject code

  • Enter at least 2 characters in the searchfield to trigger the API call
  • The default (thus omitted) setting preserveHTML:true in the first example results in instantly getting an alert message
  • It also injects hidden code into an additional click event handler on a search item (marked red). Try to click it as you would usually do when selecting the desired search result
  • The evil example code removes itself from the DOM after being executed once

Vulnerable Version

$('.ui.search.evilexample') .search({ apiSettings: { url: '/evilapi.json' }, fields: { title : 'name' }, minCharacters : 2 });

Sanitized Version

$('.ui.search.evilexample_sanitized') .search({ preserveHTML : false, apiSettings: { url: '/evilapi.json' }, fields: { title : 'name' }, minCharacters : 2 });

Dimmer Message
Dimmer sub-header