This library requires Bootstrap 3 and jQuery 1.8+ to work
Download the latest release by clicking here and unzip its contents in your assets folder
Copy and paste the following code, replacing the paths where needed. Make sure that
magicsuggest-min.js
is declared after jQuery:
<link href="assets/magicsuggest/magicsuggest-min.css" rel="stylesheet">
<script src="assets/magicsuggest/magicsuggest-min.js"></script>
Remember that it is good practice to declare the javascript at the end.
For example, in your form, create a div
or input
tag:
<div id="magicsuggest"></div>
Create a script to configure the component. For example:
$(function() {
$('#magicsuggest').magicSuggest({
[...] // configuration options
});
});
allowFreeEntries
allows the user to enter non-suggested entries.
By default the user can enter any input that he wants. Entering text will filter down the suggestions to the available matches.
When set to false
, this parameter either restricts the user to the given suggestions (in which case pressing ENTER will not trigger anything).
When set to true
, this parameter allows the user to enter custom entries and have them be added to his selected values.
allowFreeEntries
set to false:
$('#ms-allowFreeEntries').magicSuggest({
allowFreeEntries: false,
data: ['Paris', 'New York', 'Gotham']
});
allowDuplicates
allows the user to reenter the same entry multiple times.
By default the user cannot enter the same value twice.
When set to true
, each value can be entered multiple times.
allowDuplicates
set to true:
$('#ms-allowDuplicates').magicSuggest({
allowDuplicates: true,
data: ['Paris', 'New York', 'Gotham']
});
ajaxConfig
specifies the way ajax calls are made.
The component uses jQuery's underlying $.ajax()
method that can be further configured by passing this property.
This is useful for example when one needs to add converters or perform cross-site requests.
ajaxConfig
set to add xhrFields
field:
$('#ms-ajaxConfig').magicSuggest({
data: 'http://nicolasbize.com/magicsuggest/get_cities.php',
ajaxConfig: {
xhrFields: {
withCredentials: true,
}
}
});
autoSelect
automatically selects a result if only one match is found.
As the user types in the combo, the combo's contents will most likely end up displaying a single suggestion.
This parameter will automatically add it to the selection when Enter
is pressed. When set to false
,
the user has to use the keyboard arrows or the mouse to make his selection.
autoSelect
set to false
:
$('#ms-autoSelect').magicSuggest({
autoSelect: false,
allowFreeEntries: false,
data: ['Paris', 'New York', 'Gotham']
});
beforeSend
if a custom jQuery function that is launched prior to the ajax request.
From jQuery's doc: A pre-request callback function that can be used to modify the XMLHTTPRequest object before it is sent.
Use this to set custom headers, etc. The jqXHR and settings objects are passed as arguments. This is an Ajax Event.
Returning false
in the beforeSend function will cancel the request
Defaults to function(){ }
beforeSend
set to cancel the request :
$('#ms-beforeSend').magicSuggest({
data: 'wrong_url.php',
beforeSend: function(xhr, settings) {
return false;
}
});
cls
specifies an additional CSS class to apply to the container element.
When the MagicSuggest component is rendered, the input field is surrounded with a div container that has a base class called
ms-ctn
. By specifying a custom class, it will be put next to the ms-ctn
specifications, thus enabling you to override the base CSS settings.
cls
set to custom to render a blue combo with a flat square style :
/** Custom style to place in a CSS declaraction **/
.custom, .custom input {
color: blue;
background: #ECEEFF !important;
border-radius: 0 !important;
}
$('#ms-cls').magicSuggest({
cls: 'custom'
});
data
provides the entries to fill up the combo box.
MagicSuggest's combo is filled with JSON records that have at least a name and an id. The records can hold as many information as
you need, but by default the component displays some text and associates a value to it. The data
parameter is there to provide
the necessary info to fill up the combo as the user searches through suggestions. Expected value formats for the parameter include:
['Paris', 'New York']
data: [{"id":"Paris", "name":"Paris"}, {"id":"New York", "name":"New York"}]
.
[{"id":0, "name":"Paris"}, {"id":1, "name":"New York"}]
[{id:0, name:"Paris"}, {id:1, name:"New York"}]
results
property: {"results": [{"id":0, "name":"Paris"}, {"id":1, "name":"New York"}]}
{"results": [{id:0, name:"Paris"}, {id:1, name:"New York"}]}
The data can be provisionned in a static way or in a dynamic way:
allowFreeEntries
is set to true (default value).
data
property, MagicSugest will perform an ajax request to retrieve the data necessary to populate the combo box.
The request will include a query
parameter containing the text that the user has typed, thus giving the server
enough information to send back narrowed results. Make sure the results match one of the expected value format.
query
for ajax)
$('#ms-data-no-data').magicSuggest({});
$('#ms-data-static-data').magicSuggest({
data: [{"id":0, "name":"Paris"}, {"id":1, "name":"New York"}]
});
$('#ms-data-ajax').magicSuggest({
data: 'get_cities.php'
});
$('#ms-data-function').magicSuggest({
data: function(q){
var e = q || '', r=[], c = ['Paris', 'New York', 'Gotham'];
for(var i=0; i<c.length; i++){
if(c[i].toLowerCase().indexOf(e.toLowerCase()) > -1)
r.push({id: i, name: c[i]});
}
return r;
}
});
dataUrlParams
adds additionals parameters given to the ajax call.
When performing an ajax call through the data
's specified URL, MagicSuggest will pass a base parameter called query
containing the current text entered by the user. All parameters and values specified in the dataUrlParams
will also be passed along.
This can be especially useful in a form if the combo's suggestions depend upon a prior field.
dataUrlParams
set to pass out some random info :
$('#ms-dataUrlParams').magicSuggest({
data: 'get_cities.php',
dataUrlParams: { id: 34 }
});
disabled
initializes the combo in a disabled state.
When disabled, the user is not able to change the combo's selection or to interact with the component.
disabled
set to true :
$('#ms-disabled').magicSuggest({
data: ['Paris', 'New York', 'Gotham'],
disabled: true
});
disabledField
specifies the JSON property that defines the disabled behaviour.
When specified, each record may have that specific property that triggers a disabled item if set to true
.
disabledField
set to a newly given 'disabled' property in the JSON results:
$('#ms-disabledField').magicSuggest({
data: [{id:0, name:'Male', disabled: true}, {id:1, name:'Female'}],
disabledField: 'disabled'
});
displayField
specifies the JSON property to be used for display.
When providing records to the combo, the component needs to know which object property to display. This property allows you to specify a custom record property.
displayField
set to gender :
$('#ms-displayField').magicSuggest({
data: [{id:0, gender:'Male'}, {id:1, gender:'Female'}],
displayField: 'gender'
});
editable
enables or prevents keyboard interaction.
When set to false, the user can only make selections by clicking on the combobox or its right trigger.
Setting this setting to false will set expandOnFocus
's default to true.
editable
set to false :
$('#ms-editable').magicSuggest({
data: ['Paris', 'New York', 'Gotham'],
editable: false
});
expanded
sets the starting state for the combo.
When set to true, the combo will be expanded as soon as its data is loaded upon startup.
expanded
set to true :
$('#ms-expanded').magicSuggest({
data: ['Paris', 'New York', 'Gotham'],
expanded: true
});
expandOnFocus
automatically expands the combo upon focus.
When set to true, the combo will be expand when clicked upon or when focus is gained through keyboard's tab. Also, because the focus is kept when making a selection, the combo will stay expanded until the focus is lost. This is useful when the user needs to make several selections fast.
expandOnFocus
set to true :
$('#ms-expandOnFocus').magicSuggest({
data: ['Paris', 'New York', 'Gotham'],
expandOnFocus: true
});
groupBy
specifies the JSON property to be used for grouping.
MagicSuggest allows the combo's contents to be grouped by categories. The records that need to be grouped should contain their category as a property. Look at data.json and data-groupby.json to see an example of the data passed to the component.
groupBy
set to 'country'
:
$('#ms-groupBy').magicSuggest({
data: 'data.json',
groupBy: 'country'
});
$('#ms-groupBy2').magicSuggest({
data: 'data-groupby.json',
groupBy: 'country.name'
});
hideTrigger
hides the right trigger.
When hiding the trigger, the combo becomes expanded when:
expandOnFocus
is set to truehideTrigger
set to true
:
$('#ms-hideTrigger').magicSuggest({
data: 'data.json',
hideTrigger: true
});
highlight
emphasizes the typed text in the combo's suggestions.
As the combo's contents get filtered as the user types what he is looking for, highlighting helps the user visually see why the combo's choices are there. This default setting can be turned off using this parameter.
highlight
set to false
:
$('#ms-highlight').magicSuggest({
data: 'data.json',
highlight: false
});
id
gives the component a specific identifier.
If you need to access the component from anywhere in the code, you can give it its own id. This enables you to call upon it to retrieve its properties / methods / events after the component has been created.
id
set to 'my-custom-id'
:
var myCustomId = $('#ms-id').magicSuggest({
data: ['Paris', 'New York', 'Gotham'],
id: 'my-custom-id'
});
$($('#my-custom-id').magicSuggest()).on(
'selectionchange', function(e, cb, s){
alert(s);
}
);
infoMsgCls
adds a class to the information text.
MagicSuggest includes a tiny information text that is displayed on the top-right corner of the component. While this text
can be hidden / disabled, it can be a great helper for the user to understand or see live-validation of his choices.
infoMsgCls
enables you to customize the way that it looks.
infoMsgCls
set to custom
:
$('#ms-infoMsgCls').magicSuggest({
data: ['Paris', 'New York', 'Gotham'],
infoMsgCls: 'custom'
});
inputCfg
adds properties to the input dom element.
Some external libraries such as AngularJS require the input fields to be configured in a particular way.
This parameter allows additional parameters which will be passed down to the input dom element.
It is advised to pass JSON and not just Object Literal Notation for this parameter.
inputCfg
set to {"ng-model":"customer.city"}
:
$('#ms-inputCfg').magicSuggest({
data: ['Paris', 'New York', 'Gotham'],
inputCfg: {"ng-model":"customer.city"}
});
invalidCls
specifies the class to be used to style an invalid entry.
When the method validate
is called, the container style can be modified through the use of a custom
class appended only when the validation fails.
invalidCls
set to {"ng-model":"customer.city"}
:
$('#ms-invalidCls').magicSuggest({
data: ['Paris', 'New York', 'Gotham'],
required: true,
invalidCls: 'custom'
});
matchCase
filters data using case sensitivity.
When mode
is set to local
, MagicSuggest takes care of filtering the records to display.
This parameter sets the case sensitivity for that filtering process.
matchCase
set to true
:
$('#ms-matchCase').magicSuggest({
data: ['Paris', 'New York', 'Gotham'],
matchCase: true
});
maxDropHeight
defines how tall the expanded combobox can be.
The size is set in pixels. Once expanded, the combo's height will try and take as much room as possible to display all of its records. In case there are too many results displayed, this parameter will limit the given size.
maxDropHeight
set to 145
px :
$('#ms-maxDropHeight').magicSuggest({
data: 'data.json',
maxDropHeight: 145
});
maxEntryLength
defines the max number of characters for free entries.
When allowFreeEntries
is set to true
, this parameter will limit the size in characters of an entry
that can be set by the user. Set to null
if you do not want any limit.
maxEntryLength
set to 5
:
$('#ms-maxEntryLength').magicSuggest({
maxEntryLength: 5
});
maxEntryRenderer
sets the helper message for entries that are too long.
A helper message is displayed when the user goes beyond the maxEntryLength
parameter. The message is
defined by a function that takes the entry as its only argument.
Defaults to function(v){ return 'Please reduce your entry by ' + v + ' character' + (v > 1 ? 's':'');}
maxEntryRenderer
set to display a friendlier message :
$('#ms-maxEntryRenderer').magicSuggest({
maxEntryLength: 5,
maxEntryRenderer: function(v) {
return 'TOO LONG DUMMY!!';
}
});
maxSuggestions
defines how many items the combo box can display at once.
Because data
may hold thousands of records, you may want to restrict the maximum amount of items
displayed in the combo, thus making its scrollbar usable. Note that while the items are not all shown in the combo,
they are still kept in memory and can be accessed or displayed if the contents is being filtered.
maxSuggestions
set to 10 :
$('#ms-maxSuggestions').magicSuggest({
data: 'data.json',
maxSuggestions: 3
});
maxSelection
sets the limit of items that can be selected.
Set this to 1
to get the behaviour of a classic combo box. Set this to null
to remove the limit.
Once the limit has been reached, a message specified by maxSelectionRenderer
will be displayed in the helper
section to notify the user.
maxSelection
set to 3 :
$('#ms-maxSelection').magicSuggest({
maxSelection: 3
});
method
sets the HTTP protocol method.
get
to include the query parameters in the URL of a GET request.post
to include the query parameters in the message body of a POST request.method
set to get
:
$('#ms-method').magicSuggest({
method: 'get',
data: 'get_cities.php'
});
minChars
defines the minimum amount of characters before expanding the combo.
When there is a lot of data, filtering and sorting may take some time so it may sometimes be wise to ask for a couple of characters before processing and displaying the results.
minChars
set to 2
:
$('#ms-minChars').magicSuggest({
minChars: 2,
data: 'data.json'
});
minCharsRenderer
sets the helper message for input that is too short.
A helper message is displayed when the user needs to type more characters before seeing any results into the combo.
The message is defined by a function that takes the entry as its only argument.
Defaults to function(v){ return 'Please type ' + v + ' more character' + (v > 1 ? 's':'');}
minCharsRenderer
set to display a heroic message
:
$('#ms-minCharsRenderer').magicSuggest({
minChars: 2
minCharsRenderer: function(v){
return 'Be more precise Spiderman!!';
},
data: 'data.json'
});
name
used in the current form.
When this component is included in a form, its value is passed along with other form components to be processed by the server.
This parameter allows you to identify the resources in the post
or get
request that is done on the server.
Because the component allows for multiple selections, it behaves just like a checkbox
input element. Therefore, the real
name used is in the form of an array like fruits[]
. You may pass your string in the form cities
or cities[]
,
the hidden inputs that behave like checkboxes will have cities[]
for name.
name
set to tags
:
$('#ms-name').magicSuggest({
name: 'tags'
});
noSuggestionText
is the text displayed when no match is found.
When the user starts typing inside the combo, its content is being filtered (either server or client side, see mode
).
When no match is found, the helper is updated with this parameter. The default value is 'No suggestions'
. Note that you can use {{query}}
to reflect the user input, as shown in the example.
noSuggestionText
set to 'No result matching the term [...]'
:
$('#ms-noSuggestionText').magicSuggest({
noSuggestionText: 'No result matching the term {{query}}',
data: ['Paris', 'New York', 'Gotham']
});
placeholder
is the text displayed when the combo is empty.
When no selection has been performed, the combo will display this string. Set to ''
if you do not
wish to see any strings placed.
placeholder
set to 'Make a selection'
:
$('#ms-placeholder').magicSuggest({
placeholder: 'Make a selection',
data: ['Paris', 'New York', 'Gotham']
});
queryParam
defines the name of the parameter sent through ajax.
This parameter allows you to customize the name of the parameter sent to the server whose value is the current input string as entered by the user.
queryParam
set to 'q'
:
$('#ms-queryParam').magicSuggest({
queryParam: 'q',
data: 'get_cities.php'
});
renderer
will format the combo's results with custom HTML.
This parameter allows you to customize the way that the combo items are presented. You may pass a function whose parameter will be the current suggestion value. Make sure to render a proper closure in the given HTML or you will break the combo's DOM layout.
renderer
set to display the country's flag in front of the city names :
$('#ms-renderer').magicSuggest({
renderer: function(data){
var file = data.country === 'France' ? 'fr.png' : 'us.png';
var img = 'assets/images/' + file;
return '<img class="i" src="' + img + '"/>' + data.name;
},
allowFreeEntries: false,
data: 'data.json'
});
required
ensures that at least one selection has been made.
When set to true, the validation performed on the component will return false if no selection has been made.
required
set to true
:
$('#ms-required').magicSuggest({
required: true
});
resultAsString
displays the selection as delimited string.
To get a look that is cleaner and ressembling a regular textbox, this option will change the DOM used to render the selected
items and render them as a single string separated by default by commas (see resultAsStringDelimiter
) when the component looses its focus.
resultAsString
set to true
:
$('#ms-resultAsString').magicSuggest({
resultAsString: true,
data: 'data.json'
});
resultAsStringDelimiter
specifies how the string will be delimited.
When displaying the results as a string, this parameter specifies how each result element is delimited.
By default, it is a comma-separated values like the GMail recipients combo box.
resultAsStringDelimiter
set to ';'
:
$('#ms-resultAsStringDelimiter').magicSuggest({
resultAsStringDelimiter: ';',
resultAsString: true
});
resultsField
specifies the JSON property that contains the suggestions data.
When data
is given a JSON object (and not array), the component needs to know which property to inspect for
its data. This parameter allows you to specify where to look in the object.
resultsField
set to cities
:
$('#ms-resultsField').magicSuggest({
resultsField: 'cities',
data: 'object.json'
});
selectFirst
auto places the cursor on the first item.
When set to true, the combo's keyboard cursor will automatically select the first element when multiple elements are returned. This allows the user to quickly hit Enter
after his search query.
selectFirst
set to true
:
$('#ms-selectFirst').magicSuggest({
selectFirst: true,
resultsField: 'cities',
data: 'object.json'
});
selectionCls
modifies the way selections look.
Current selections are made to look like tags with a small deletion button in the form of an x. This property lets you customize they way that each selected item is being rendered.
selectionCls
set to 'custom'
:
$('#ms-selectionCls').magicSuggest({
selectionCls: 'custom',
data: ['Paris', 'New York', 'Gotham']
});
selectionContainer
specifies where the results are rendered.
Specifies where the selection is rendered. When not specified, the selection is rendered in a newly created DOM element according
to selectionPosition
selectionContainer
set to $('#custom-ctn')
:
$('#ms-selectionContainer').magicSuggest({
selectionContainer: $('#custom-ctn'),
data: ['Paris', 'New York', 'Gotham']
});
selectionPosition
defines where the selected items should be rendered.
Either 'right'
, 'bottom'
or 'inner'
are accepted values. This parameter
specifies where the selection should be rendered.
selectionPosition
set to 'bottom'
:
$('#ms-selectionPosition').magicSuggest({
selectionPosition: 'bottom',
data: ['Paris', 'New York', 'Gotham']
});
selectionRenderer
defines how the selected items should be displayed.
Besides adding a CSS class with selectionCls
, you can also change the generated DOM for each item.
This allows you to display additional information or customize the rendered item any way you want.
selectionRenderer
set to show the country flag :
$('#ms-selectionRenderer').magicSuggest({
selectionRenderer: function(data){
var file = data.country === 'France' ? 'fr.png' : 'us.png';
var img = 'assets/images/' + file;
return '<img class="i" src="' + img + '"/>' + data.name;
},
allowFreeEntries: false,
data: 'data.json'
});
selectionStacked
will stack the selection vertically.
Useful when you have limited horizontal space, such as on a sidebar filter for example. Note that this requires
selectionPosition
to be set to either 'bottom'
or 'right'
.
selectionStacked
set to true :
$('#ms-selectionStacked').magicSuggest({
selectionStacked: true,
selectionPosition: 'bottom',
data: 'data.json'
});
sortDir
sorts data in a given direction.
The parameter only accepts values 'asc'
and 'desc'
.
When mode
is set to 'manual'
, the component takes care of sorting and filtering data.
This parameter changes the way that the data is sorted.
sortDir
set to 'desc'
:
$('#ms-sortDir').magicSuggest({
sortDir: 'desc',
sortOrder: 'name',
data: 'data.json'
});
sortOrder
sorts data according to a given property field.
When given JSON objects in the data
parameter, and with the mode
set to 'local'
,
the component will attempt to sort the given data. This property allows the data to be sorted according to any given property
found on all JSON results.
sortOrder
set to 'name'
:
$('#ms-sortOrder').magicSuggest({
sortOrder: 'name',
data: 'data.json'
});
strictSuggest
filters out entries that do not start with the given input.
The default behaviour is to look throughout all entries to see if it contains, as a substring, the input entered by the user. This parameter ensures that the entries suggested start with the given input.
strictSuggest
set to true
:
$('#ms-strictSuggest').magicSuggest({
strictSuggest: true,
data: ['Henry Ford', 'Thierry Henry', 'Harrison Ford']
});
style
adds inline CSS to the component's container.
While you can add custom classes using the cls
parameter, you may also add inline style using this parameter.
The style is applied to the component's container (ie. what looks like a regular bootstrap textbox)
style
set to make the border in a straight angle:
$('#ms-style').magicSuggest({
style: 'border-radius: 0 !important',
data: ['Paris', 'New York', 'Gotham']
});
toggleOnClick
expands the component when clicked upon.
When set to true
, the combo will expand no matter where the user clicks on the combobox. This is useful if
you do not allow the user to type in the combo using the editable
property.
toggleOnClick
set to true
:
$('#ms-toggleOnClick').magicSuggest({
toggleOnClick: true,
data: ['Paris', 'New York', 'Gotham']
});
typeDelay
sets the time in ms before triggering AJAX calls.
To prevent the component from making too many queries, it waits for some time after the user's last keypress to send
the AJAX request. You can actually set this parameter to 0
if you do not want the component to wait. In that
case, it will make one query everytime a key is pressed within the component.
typeDelay
set to 0
:
$('#ms-typeDelay').magicSuggest({
typeDelay: 0,
data: 'get_cities.php'
});
useTabKey
makes Tab behave like Enter.
By setting this parameter to true
, the tab
key will not loose the focus but will
add a selection made by the user to the current selections.
useTabKey
set to true
:
$('#ms-useTabKey').magicSuggest({
useTabKey: true
});
useCommaKey
makes Comma behave like Enter.
By setting this parameter to true
, the ,
key will add a selection made by the
user to the current selections.
useCommaKey
set to true
:
$('#ms-useCommaKey').magicSuggest({
useCommaKey: true
});
useZebraStyle
renders odd lines with more shades of grey.
While set to true
, odd lines will be given the additional class ms-res-odd
which by default
is a darker gray to have lines stand out better.
useZebraStyle
set to true
:
$('#ms-useZebraStyle').magicSuggest({
useZebraStyle: true,
data: 'data.json'
});
value
sets an initial value.
Because the component generates an array of values, it expects an array of values as well. Make sure that
valueField
is properly set if the value field in your JSON records is different than id
.
value
set to match the hottest places:
$('#ms-value').magicSuggest({
value: [1,7,16,19],
data: 'data.json'
});
valueField
specifies the JSON property to be used for value.
When providing records to the combo, the component needs to know which object property to take as value. This property allows you to specify a custom record property.
valueField
set to 'name'
:
var ms = $('#ms-valueField').magicSuggest({
valueField: 'name',
data: 'data.json'
});
$(ms).on(
'selectionchange', function(e, cb, s){
alert(cb.getValue());
}
);
vregex
regulates the type of entries set.
You can add a custom regular expression to tell the component which entries should be considered valid or not.
This is useful if your entries do not validate against a classic vtype
vregex
set to only accept values that have 1-5 chars:
var ms = $('#ms-vregex').magicSuggest({
vregex: /^[a-z0-9_-]{1,5}$/
});
$(ms).on(
'selectionchange', function(e, cb, s){
alert("valid: " + this.isValid());
}
);
vtype
requires an entry to match a given type.
Accepted values are: alpha
, alphanum
, email
, url
, ipaddress
.
vtype
set to only accept ip addresses:
var ms = $('#ms-vtype').magicSuggest({
vtype: 'ipaddress'
});
$(ms).on(
'selectionchange', function(e, cb, s){
alert("valid: " + this.isValid());
}
);
addToSelection([object] objs, [boolean] silent)
adds items to the selection.
This method adds one or multiple items to the current selection.
objs
can either be an array of JSON records or an array of values. In the case of values, make sure
that the component is aware of what records these values correspond to.silent
can shut off the triggered events as elements are being added to the combo.addToSelection
set to add a couple of items to the initial value:
var ms = $('#ms-addToSelection').magicSuggest({
data: 'data.json',
value: [1,2]
});
ms.addToSelection([3,4,5]);
clear([boolean] silent)
the selection.
This method empties the component's selection.
silent
can shut off the triggered events as elements are cleared.clear
set to clear the initial values:
var ms = $('#ms-clear').magicSuggest({
data: 'data.json',
value: [1,2]
});
ms.clear();
collapse([boolean] silent)
the combo.
This method collapses the combo if it is expanded.
silent
can shut off the triggered events as the combo is collapsed.collapse
set to collapse the collapse a combo that was initialized expanded:
var ms = $('#ms-collapse').magicSuggest({
data: ['Paris', 'New York', 'Gotham'],
expanded: true
});
ms.collapse();
disable()
the combo.
This method disables the combo.
disable
:
var ms = $('#ms-disable').magicSuggest({});
ms.disable();
empty()
what the user was typing.
This method clears the value contained in the input
tag.
empty
performed whenever a key is typed:
var ms = $('#ms-empty').magicSuggest({});
$(ms).on('keyup', function(){
this.empty();
});
ms.empty();
enable()
the combo.
This method enables a component that might have been in a disabled state.
enable
performed at startup:
var ms = $('#ms-enable').magicSuggest({
disabled: true
});
ms.enable();
expand()
the component.
This method expands a component that might have been in a disabled state.
expand
performed at startup:
var ms = $('#ms-expand').magicSuggest({});
ms.expand();
getData()
returns the combo suggestions.
This method returns all the suggestions contained in the combo box.
getData
upon selection:
var ms = $('#ms-getData').magicSuggest({
data: ['Paris', 'New York', 'Gotham']
});
$(ms).on('selectionchange', function(){
alert(JSON.stringify(ms.getData()));
});
isDisabled()
returns the status of the component.
This method isDisabled returns wheter or not the component is in a disabled state.
isDisabled
performed at startup:
var ms = $('#ms-isDisabled').magicSuggest({
disabled: true,
data: ['Paris', 'New York']
});
if(ms.isDisabled()){
ms.setValue(['Paris']);
}
isValid()
checks if the selection is valid.
This method checks if each entry given by the user is valid. The field is invalid if any item is invalid
(ie. not matching a vtype
or vregex
, or it is empty even though it is marked as required)
isValid
performed whenever the user adds custom email addresses:
var ms = $('#ms-isValid').magicSuggest({
vtype: 'email'
});
$(ms).on('selectionchange', function(){
alert("valid: " + this.isValid());
});
getDataUrlParams()
returns the list of extra URL paramaters set for AJAX requests.
This method simply returns the parameters that the component sends on each AJAX request.
getDataUrlParams
performed at startup:
var ms = $('#ms-getDataUrlParams').magicSuggest({
dataUrlParams: {id: 3}
});
$(ms).on('selectionchange', function(){
alert(this.getDataUrlParams().id);
});
getName()
returns the name used for HTML form submission.
This method checks if each entry given by the user is valid.
getName
performed whenever the user selects a city:
var ms = $('#ms-getName').magicSuggest({
name: 'cities',
data: 'data.json'
});
$(ms).on('selectionchange', function(){
alert("name:" + this.getName());
});
getSelection()
returns an array of selected JSON objects.
The objects passed to the component through the data
parameter (whether static or through a dynamic AJAX call) are
stored within the component. Whenever the user selects an item within the combo, it becomes part of the user selection. Those items
can be retrieved using this method and then serialized before being sent to the server.
getSelection
performed whenever the user selects a city:
var ms = $('#ms-getSelection').magicSuggest({
data: 'data.json'
});
$(ms).on('selectionchange', function(){
alert(JSON.stringify(this.getSelection()));
});
getRawValue()
returns the current text being entered by the user.
The visual component is always made of a container with seperate DOMs for the user selection and what he is currently
entering on his keyboard. This method returns the value contained into that input
element.
getRawValue
performed when a word gets too long:
var ms = $('#ms-getRawValue').magicSuggest({});
$(ms).on('keyup', function(){
if(ms.getRawValue().length > 4){
alert("it's too big!");
}
});
getValue()
returns an array containing only the selected JSON values.
While getSelection()
returns an array containing the full objects, this method only returns
the value as defined by the valueField
property.
getValue
performed whenever someone makes a selection:
var ms = $('#ms-getValue').magicSuggest({
data: 'data.json'
});
$(ms).on('selectionchange', function(){
alert(JSON.stringify(this.getValue()));
});
removeFromSelection([object] objs, [boolean] silent)
removes items from the selection.
Removes one or multiple JSON objects from the current selection. Set boolean
to true
if you don't want the component to trigger an event when performing that change.
removeFromSelection
performed whenever someone makes a selection:
var ms = $('#ms-removeFromSelection').magicSuggest({
data: 'data.json'
});
$(ms).on('selectionchange', function(){
this.removeFromSelection(this.getSelection(), true);
alert('Choose something else. Glory to Arstotzka!');
});
setData([array] cbItems)
sets the objects listed in the combo.
.
setData
set at startup:
var ms = $('#ms-setData').magicSuggest({});
ms.setData(['Paris', 'New York', 'Gotham']);
$(ms).on('selectionchange', function(){
alert(JSON.stringify(this.getSelection()));
this.setData([
{id:1, name:'Blue'},
{id:2, name:'Red'}
]);
});
setName([string] name)
sets the name to be used for form
submission.
This will set the name for the form component. Please remember that this component behaves like a lot of checkboxes
that have the same name, like <input type="checkbox" name="cities[]" value="Paris"/>
The name will always be in an array form so that the passed values can be interpreted as an array of values,
just like if you were dealing with a bunch of checkboxes. In the following example, setting the name to cities[]
would have resulted in the same DOM.
setName
set to 'cities'
:
var ms = $('#ms-setName').magicSuggest({
data: 'data.json'
});
ms.setName('cities');
$(ms).on('selectionchange', function(){
alert(this.getName());
});
setSelection(object[])
sets the selection with a given array of objects.
This method allows you to set the current selection by providing an array of JSON objects.
setSelection
used to add free entries at startup:
var ms = $('#ms-setSelection').magicSuggest({});
ms.setSelection([{name:'Paris', value:1}]);
setValue([array] ids)
sets the selection according to given values.
This method allows you to set the current selection by providing an array of values. Those values must match
what can be found on the valueField
JSON property of the current loaded combo's records.
setValue
used to preselect cities at startup:
var ms = $('#ms-setValue').magicSuggest({
data: 'data.json'
});
ms.setValue([2, 3, 4]);
setDataUrlParams([object] params)
sets extra parameters for AJAX requests.
This method will set the additional parameters passed out to any AJAX call.
setDataUrlParams
used to add an id to the call:
var ms = $('#ms-setDataUrlParams').magicSuggest({
data: 'data.json'
});
ms.setDataUrlParams({id:3});
$(ms).on('selectionchange', function(){
alert(JSON.stringify(this.getDataUrlParams()));
});
beforeload(e, this)
is fired before the AJAX request is performed.
This event is fired just before any AJAX request is performed.
beforeload
:
var ms = $('#ms-beforeload').magicSuggest({
data: 'data.json'
});
$(ms).on('beforeload', function(c){
console.debug(this);
});
blur(e, this)
is fired when the component looses focus.
This event is always triggered when the component looses its focus.
blur
:
var ms = $('#ms-blur').magicSuggest({});
$(ms).on('blur', function(c){
alert('where are you going?');
});
collapse(e, this)
is fired when the combo is collapsed.
This event is triggered when the component has been collapsed, either through clicking the mouse on the trigger or by clicking on another component that can be focused.
oncollapse
:
var ms = $('#ms-oncollapse').magicSuggest({
data: 'get_cities.php'
});
$(ms).on('collapse', function(c){
alert('now closed. come back tomorrow.');
});
expand(e, this)
is fired when the combo is expanded.
This event is fired when the component is expanded, either through its trigger, or when the user starts typing.
onexpand
:
var ms = $('#ms-onexpand').magicSuggest({
data: 'get_cities.php'
});
$(ms).on('expand', function(c){
alert('now open for business.');
});
focus(e, this)
is fired when the combo gains focus.
This event is triggered whenever the component gains focus, whether through the keyboard with the tab
key,
or with the mouse.
onfocus
:
var ms = $('#ms-onfocus').magicSuggest({});
$(ms).on('focus', function(c){
alert('Turning blue, I think i have the flu!');
});
keydown(e, this, keyevent)
is fired when the user presses a key.
this event is triggered as soon as the user presses a key while the component has focus.
onkeydown
:
var ms = $('#ms-onkeydown').magicSuggest({});
$(ms).on('keydown', function(e,m,v){
alert('Key code # ' + v.keyCode);
});
keyup(e, this, keyevent)
is fired when the user releases a key.
This event is triggered whenever the pressed key has been released.
onkeyup
:
var ms = $('#ms-onkeyup').magicSuggest({});
$(ms).on('keyup', function(e, m, v){
alert('Key code # ' + v.keyCode);
});
load(e, this, records[])
is fired when the AJAX request has been performed.
This event is fired when the AJAX request has been completed.
load
:
var ms = $('#ms-onload').magicSuggest({
data: 'get_cities.php',
minChars: 1
});
$(ms).on('load', function(e,m){
alert('finished loading!');
});
selectionchange(e, this, records[])
is fired when the user has changed the selection.
This event is fired whenever the user changes the current selection.
selectionchange
:
var ms = $('#ms-onselectionchange').magicSuggest({
data: 'get_cities.php'
});
$(ms).on('selectionchange', function(e,m){
alert("values: " + JSON.stringify(this.getValue()));
});
triggerclick(e, this)
is fired when the user has changed the selection.
This event is fired whenever the user clicks on the trigger on the side of the component.
triggerclick
:
var ms = $('#ms-ontriggerclick').magicSuggest({
data: 'get_cities.php'
});
$(ms).on('triggerclick', function(e,m){
alert("don't shoot me!");
});