select2 bootstrap 简单使用
来源:互联网 发布:问卷星和金数据哪个好 编辑:程序博客网 时间:2024/05/06 03:04
今天无意发现 bootstrap 中的下拉列表样式很好看,而且支持模糊查找.于是想研究看看发现使用select2插件
官网 http://ivaynberg.github.io/select2/index.html
Constructor
width
style attribute of the Select2 container div. The following values are supported:- off
- No width attribute will be set. Keep in mind that the container div copies classes from the source element so setting the width attribute may not always be necessary.
- element
- Uses javascript to calculate the width of the source element.
- copy
- Copies the value of the width style attribute set on the source element.
- resolve
- First attempts to copy than falls back on element.
- other values
- if the width attribute contains a function it will be evaluated, otherwise the value is used verbatim.
The minimum number of results that must be initially (after opening the dropdown for the first time) populated in order to keep the search field. This is useful for cases where local data is used with just a few results, in which case the search box is not very useful and wastes screen space.
The option can be set to a negative value
to permanently hide the search field.
Only applies to single-value select boxes
maximumSelectionSizeint/functionThe maximum number of items that can be selected in a multi-select control. If this number is less than 1 selection is not limited.
Once the number of selected items reaches the maximum specified the contents of the dropdown will be populated by the formatSelectionTooBig
function.
Initial value that is selected if no other selection is made.
The placeholder can also be specified as a data-placeholder
attribute on the select
orinput
element that Select2 is attached to.
Note that because browsers assume the first option
element is selected in non-multi-value select boxes an empty first option
element must be provided (<option></option>
) for the placeholder to work.
When attached to a select
resolves the option
that should be used as the placeholder. Can either be a function which given the select
element should return the option
element or a string first
to indicate that the first option should be used.
This option is useful when Select2's default of using the first option only if it has no value and no text is not suitable.
separatorstringSeparator character or string used to delimit ids in value
attribute of the multi-valued selects. The default delimiter is the ,
character.
Whether or not a clear button is displayed when the select box has a selection. The button, when clicked, resets the value of the select box back to the placeholder, thus this option is only available when the placeholder is specified.
This option only works when the placeholder is specified.
When attached to a select
an option
with an empty value must be provided. This is the option that will be selected when the button is pressed since a select box requires at least one selection option
.
Also, note that this option only works with non-multi-value based selects because multi-value selects always provide such a button for every selected option.
multiplebooleanWhether or not Select2 allows selection of multiple values.
When Select2 is attached to a select
element this value will be ignored and select
'smultiple
attribute will be used instead.
If set to false the dropdown is not closed after a selection is made, allowing for rapid selection of multiple items. By default this option is set to true
.
Only applies when configured in multi-select mode.
openOnEnterbooleanIf set to true the dropdown is opened when the user presses the enter key and Select2 is closed. By default this option is enabled.
idfunctionFunction used to get the id from the choice object or a string representing the key under which the id is stored.id(object)
id
property that is returned.matcherfunctionUsed to determine whether or not the search term matches an option when a built-in query function is used. The built in query function is used when Select2 is attached to a select
, or thelocal
or tags
helpers are used.matcher(term, text, option)
option
element we are trying to match. Only given when attached to select
. Can be used to match against custom attributes on the option
tag in addition to matching on the option
's text.<returns>booleantrue
if search term matches the text, or false
otherwise.The default implementation is case insensitive and matches anywhere in the term:function(term, text) { return text.toUpperCase().indexOf(term.toUpperCase())>=0; }
sortResultsfunctionUsed to sort the results list for searching right before display. Useful for sorting matches by relevance to the user's search term.sortResults(results, container, query).objectobjectOne of the result objects returned from the
query
functioncontainerjQuery objectjQuery wrapper of the node that should contain the representation of the result.queryobjectThe query object used to request this set of results.<returns>objectA results object.Defaults to no sorting: function(results, container, query) { return results; }
formatSelectionfunctionFunction used to render the current selection.formatSelection(object, container)
query
function.containerjQuery objectjQuery wrapper of the node to which the selection should be appended.escapeMarkupfunctionFunction that can be used to escape html markup. This is the function defined in the escapeMarkup
option, or the default.<returns>string (optional)Html string, a DOM element, or a jQuery object that renders the selection.The default implementation expects the object to have a text
property that is returned.
The implementation may choose to append elements directly to the provided container
object, or return a single value and have it automatically appended.
When attached to a select
the original <option>
(or <optgroup>) element is accessible inside the specified function through the property item.element
:
format(item) { var originalOption = item.element; return item.text}formatResultfunctionFunction used to render a result that the user can select.
formatResult(object, container, query)
query
function.containerjQuery objectjQuery wrapper of the node that should contain the representation of the result.queryobjectThe query object used to request this set of results.escapeMarkupfunctionFunction used to escape markup in results. If you do not expect to render custom markup you should pass your text through this function to escape any markup that may have been accidentally returned. This function is configurable in options of select2.<returns>string (optional)Html string, a DOM element, or a jQuery object that represents the result.The default implementation expects the object to have a text
property that is returned.
The implementation may choose to append elements directly to the provided container
object, or return a single value and have it automatically appended.
When attached to a select
the original <option>
(or <optgroup>) element is accessible inside the specified function through the property item.element
:
format(item) { var originalOption = item.element; return item.text}formatResultCssClassfunctionFunction used to add css classes to result elements.
formatResultCssClass(object)
query
function.<returns>string (optional)String containing css class names separated by a space.By default when attached to a select
css classes from option
s will be automatically copied.
Function used to render the message
formatNoMatches(term)
Function used to render the message that is displayed while search is in progress.
formatSearching()
null
/undefined
to disable the message.formatInputTooShortstring/functionString containing "Search input too short" message, orFunction used to render the message.
formatInputTooShort(term, minLength)
Function used to render the message.
formatInputTooLong(term, maxLength)
Function used to render the message.
formatSelectionTooBig(maxSize)
Function used to render the message.
formatLoadMore(pageNumber)
createSearchChoice(term)
id
attribute.If the function returns undefined
or null
no choice will be created. If a new choice is created it is displayed first in the selection list so that user may select it by simply pressing enter
.When used in combination with input[type=hidden]
tag care must be taken to sanitize the id
attribute of the choice object, especially stripping ,
as it is used as a value separator.
createSearchChoice
. The following values are supported:- top
- Insert in the top of the list
- bottom
- Insert at the end of the list
- <function>
A custom function. For example if you want to insert the new item in the second position:
$("#tags").select2({ ... createSearchChoice: function(term) { ... }, createSearchChoicePosition: function(list, item) { list.splice(1, 0, item); }});
Essentially this is an id->object
mapping function.
initSelection(element, callback)
This function will only be called when there is initial input to be processed.
Here is an example implementation used for tags. Tags are the simplest form of data where the id is also the text:$("#tags").select2({ initSelection : function (element, callback) { var data = []; $(element.val().split(",")).each(function () { data.push({id: this, text: this}); }); callback(data); }});// Or for single select elements:$("#select").select2({ initSelection : function (element, callback) { var data = {id: element.val(), text: element.val()}; callback(data); }});tokenizerfunctionA tokenizer function can process the input typed into the search field after every keystroke and extract and select choices. This is useful, for example, in tagging scenarios where the user can create tags quickly by separating them with a comma or a space instead of pressing enter.
Tokenizer only applies to multi-selects.
tokenizer(input, selection, selectCallback, opts)
undefined
or null
is returned the input of the search field is unchanged.The default tokenizer will only be used if the tokenSeparators
and createSearchChoice
options are specified. The default tokenizer will split the string using any separator in tokenSeparators
and will create and select choice objects using createSearchChoice
option. It will also ignore duplicates, silently swallowing those tokens.tokenSeparatorsarrayAn array of strings that define token separators for the default tokenizer function. By default, this option is set to an empty array which means tokenization using the default tokenizer is disabled. Usually it is sensible to set this option to a value similar to [',', ' ']
.queryfunctionFunction used to query results for the search term.query(options)
results.context
field - this object will then be used as the context parameter for all calls to the query
method that will load more search results for the initial search term. The object will be reset back to null when a new search term is queried. This feature is useful when a page number is not easily mapped against the server side paging mechanism. For example, some server side paging mechanism may return a "continuation token" that needs to be passed back to them in order to retrieve the next page of search results.options.callbackfunctionCallback function that should be called with the result
object. The result object:id
and text
keys. The id
property is required, even if custom renderers are used. The object may also contain a children
key if hierarchical data is displayed. The object may also contain adisabled
boolean property indicating whether this result can be selected.result.morebooleantrue
if more results are available for the current search term.results.contextobjectA user-defined object that should be made available as thecontext
parameter to the query
function on subsequent queries to load more result pages for the same search term. See the description of options.context
parameter.In order for this function to work Select2 should be attached to a input type='hidden'
tag instead of a select
.
Example Data
{ more: false, results: [ { id: "CA", text: "California" }, { id: "AL", text: "Alabama" } ]}
Example Hierarchical Data
{ more: false, results: [ { text: "Western", children: [ { id: "CA", text: "California" }, { id: "AZ", text: "Arizona" } ] }, { text: "Eastern", children: [ { id: "FL", text: "Florida" } ] } ]}ajaxobjectOptions for the built in ajax query function. This object acts as a shortcut for having to manually write a function that performs ajax requests. The built-in function supports more advanced features such as throttling and dropping out-of-order responses.
$.ajax
. Defaults to $.ajax
if not specified. Allows the use of various ajax wrapper libraries such as: AjaxManager.urlstring/functionString containing the ajax url or a function that returns such a string.dataTypestringData type for the request. xml
, json
, jsonp
, other formats supported by jquery.quietMillisintNumber of milliseconds to wait for the user to stop typing before issuing the ajax request.cachebooleanIf set to false
, it will force requested pages not to be cached by the browser. Default is false
.jsonpCallbackstring/functionThe callback function name for a JSONP request. This value will be used instead of the random name automatically generated by jQuery. It is preferable to let jQuery generate a unique name as it'll make it easier to manage the requests and provide callbacks and error handling. You may want to specify the callback when you want to enable better browser caching of GET requests.datafunctionFunction to generate query parameters for the ajax request.data(term, page)
options.context
parameter to the query
function above.<returns>objectObject containing url parameters.resultsfunctionFunction used to build the query results object from the ajax responseresults(data, page)
data
function above.contextobjectSee options.context
parameter to the query
function above.<returns>objectResults object. See "options.callback" in the "query" function for format.paramsobject/functionAn object or a function that returns an object that contains extra parameters that will be passed to the transport. For example it can be used to set the content type:{contentType: "application/json;charset=utf-8"}
In order for this function to work Select2 should be attached to a input type='hidden'
tag instead of a select
.
For documentation of the data format see the query function.
dataarray/objectOptions for the built in query function that works with arrays.If this element contains an array, each element in the array must contain id
and text
keys.
Alternatively, this element can be specified as an object in which results
key must contain the data as an array and a text
key can either be the name of the key in data items that contains text or a function that retrieves the text given a data element from the array.
array
or a function
that returns an array of objects
or strings
. If strings
are used instead of objects
they will be converted into an object that has an id
and text
attribute equal to the value of the string
.containerCssfunction/objectInline css that will be added to select2's container. Either an object containing css property/value key pairs or a function that returns such an object.containerCssClassfunction/stringCss class that will be added to select2's container tag.dropdownCssfunction/objectInline css that will be added to select2's dropdown container. Either an object containing css property/value key pairs or a function that returns such an object.dropdownCssClassfunction/stringCss class that will be added to select2's dropdown container.dropdownAutoWidthbooleanWhen set to true
attempts to automatically size the width of the dropdown based on content inside.adaptContainerCssClassfunctionFunction that filters/renames css classes as they are copied from the source tag to the select2 container tag.adaptContainerCssClass(clazz)
null/undefined/''
to not apply it.The default implementation applies all classes without modification.adaptDropdownCssClassfunctionFunction that filters/renames css classes as they are copied from the source tag to the select2 dropdown tag.adaptDropdownCssClass(clazz)
null/undefined/''
to not apply it.The default implementation always returns null
thereby filtering out all classes.escapeMarkupfunctionString escapeMarkup(String markup)
Function used to post-process markup returned from formatter functions. By default this function escapes html entities to prevent javascript injection.
selectOnBlurbooleanSet to true
if you want Select2 to select the currently highlighted option when it is blurred.
0
which means the result list needs to be scrolled all the way to the bottom for the next page of results to be loaded. This option can be used to trigger the load sooner, possibly resulting in a smoother user experience.nextSearchTermfunctionFunction used to determine what the next search term should be.
Here is an example implementation used to display the current search term when the dropdown is opened:
function displayCurrentValue(selectedObject, currentSearchTerm) { return currentSearchTerm; } $("#e1").select2({ nextSearchTerm: displayCurrentValue });
Function can be used when the dropdown is configured in single and multi-select mode. It is triggered after selecting an item. In single mode it is also triggered after initSelection (when provided).
val
Gets or sets the selection. If the value
parameter is not specified, the id
attribute of the currently selected element is returned. If the value
parameter is specified it will become the current selection.
select
value
attribute of theoption
that should be selected.Array of the value
attributes of the option
s that should be selected. null
for empty.input[type=hidden]
""
to clear. Can only be used ifinitSelection()
was specified.An array of objects ids that should be selected. ""
to clear. Can only be used ifinitSelection()
was specified.triggerChange (optional)booleanWhether or not a change
event should be triggered. false
by default.val
method invoked on a single-select with an unset value will return ""
, while a val
method invoked on an empty multi-select will return []
.
alert("Selected value is: "+$("#e8").select2("val")); $("#e8").select2("val", "CA");
<div class="form-group"><label class="control-label visible-ie8 visible-ie9">Country</label><select name="country" id="select2_sample4" class="select2 form-control"><option value=""></option><option value="AF">Afghanistan</option><option value="AL">Albania</option><option value="DZ">Algeria</option><option value="AS">American Samoa</option><option value="AD">Andorra</option><option value="AO">Angola</option><option value="AI">Anguilla</option><option value="AQ">Antarctica</option><option value="AR">Argentina</option><option value="AM">Armenia</option><option value="AW">Aruba</option><option value="AU">Australia</option><option value="AT">Austria</option><option value="AZ">Azerbaijan</option><option value="BS">Bahamas</option><option value="BH">Bahrain</option><option value="BD">Bangladesh</option><option value="BB">Barbados</option><option value="BY">Belarus</option><option value="BE">Belgium</option><option value="BZ">Belize</option><option value="BJ">Benin</option><option value="BM">Bermuda</option><option value="BT">Bhutan</option><option value="BO">Bolivia</option><option value="BA">Bosnia and Herzegowina</option><option value="BW">Botswana</option><option value="BV">Bouvet Island</option><option value="BR">Brazil</option><option value="IO">British Indian Ocean Territory</option><option value="BN">Brunei Darussalam</option><option value="BG">Bulgaria</option><option value="BF">Burkina Faso</option><option value="BI">Burundi</option><option value="KH">Cambodia</option><option value="CM">Cameroon</option><option value="CA">Canada</option><option value="CV">Cape Verde</option><option value="KY">Cayman Islands</option><option value="CF">Central African Republic</option><option value="TD">Chad</option><option value="CL">Chile</option><option value="CN">China</option><option value="CX">Christmas Island</option><option value="CC">Cocos (Keeling) Islands</option><option value="CO">Colombia</option><option value="KM">Comoros</option><option value="CG">Congo</option><option value="CD">Congo, the Democratic Republic of the</option><option value="CK">Cook Islands</option><option value="CR">Costa Rica</option><option value="CI">Cote d'Ivoire</option><option value="HR">Croatia (Hrvatska)</option><option value="CU">Cuba</option><option value="CY">Cyprus</option><option value="CZ">Czech Republic</option><option value="DK">Denmark</option><option value="DJ">Djibouti</option><option value="DM">Dominica</option><option value="DO">Dominican Republic</option><option value="EC">Ecuador</option><option value="EG">Egypt</option><option value="SV">El Salvador</option><option value="GQ">Equatorial Guinea</option><option value="ER">Eritrea</option><option value="EE">Estonia</option><option value="ET">Ethiopia</option><option value="FK">Falkland Islands (Malvinas)</option><option value="FO">Faroe Islands</option><option value="FJ">Fiji</option><option value="FI">Finland</option><option value="FR">France</option><option value="GF">French Guiana</option><option value="PF">French Polynesia</option><option value="TF">French Southern Territories</option><option value="GA">Gabon</option><option value="GM">Gambia</option><option value="GE">Georgia</option><option value="DE">Germany</option><option value="GH">Ghana</option><option value="GI">Gibraltar</option><option value="GR">Greece</option><option value="GL">Greenland</option><option value="GD">Grenada</option><option value="GP">Guadeloupe</option><option value="GU">Guam</option><option value="GT">Guatemala</option><option value="GN">Guinea</option><option value="GW">Guinea-Bissau</option><option value="GY">Guyana</option><option value="HT">Haiti</option><option value="HM">Heard and Mc Donald Islands</option><option value="VA">Holy See (Vatican City State)</option><option value="HN">Honduras</option><option value="HK">Hong Kong</option><option value="HU">Hungary</option><option value="IS">Iceland</option><option value="IN">India</option><option value="ID">Indonesia</option><option value="IR">Iran (Islamic Republic of)</option><option value="IQ">Iraq</option><option value="IE">Ireland</option><option value="IL">Israel</option><option value="IT">Italy</option><option value="JM">Jamaica</option><option value="JP">Japan</option><option value="JO">Jordan</option><option value="KZ">Kazakhstan</option><option value="KE">Kenya</option><option value="KI">Kiribati</option><option value="KP">Korea, Democratic People's Republic of</option><option value="KR">Korea, Republic of</option><option value="KW">Kuwait</option><option value="KG">Kyrgyzstan</option><option value="LA">Lao People's Democratic Republic</option><option value="LV">Latvia</option><option value="LB">Lebanon</option><option value="LS">Lesotho</option><option value="LR">Liberia</option><option value="LY">Libyan Arab Jamahiriya</option><option value="LI">Liechtenstein</option><option value="LT">Lithuania</option><option value="LU">Luxembourg</option><option value="MO">Macau</option><option value="MK">Macedonia, The Former Yugoslav Republic of</option><option value="MG">Madagascar</option><option value="MW">Malawi</option><option value="MY">Malaysia</option><option value="MV">Maldives</option><option value="ML">Mali</option><option value="MT">Malta</option><option value="MH">Marshall Islands</option><option value="MQ">Martinique</option><option value="MR">Mauritania</option><option value="MU">Mauritius</option><option value="YT">Mayotte</option><option value="MX">Mexico</option><option value="FM">Micronesia, Federated States of</option><option value="MD">Moldova, Republic of</option><option value="MC">Monaco</option><option value="MN">Mongolia</option><option value="MS">Montserrat</option><option value="MA">Morocco</option><option value="MZ">Mozambique</option><option value="MM">Myanmar</option><option value="NA">Namibia</option><option value="NR">Nauru</option><option value="NP">Nepal</option><option value="NL">Netherlands</option><option value="AN">Netherlands Antilles</option><option value="NC">New Caledonia</option><option value="NZ">New Zealand</option><option value="NI">Nicaragua</option><option value="NE">Niger</option><option value="NG">Nigeria</option><option value="NU">Niue</option><option value="NF">Norfolk Island</option><option value="MP">Northern Mariana Islands</option><option value="NO">Norway</option><option value="OM">Oman</option><option value="PK">Pakistan</option><option value="PW">Palau</option><option value="PA">Panama</option><option value="PG">Papua New Guinea</option><option value="PY">Paraguay</option><option value="PE">Peru</option><option value="PH">Philippines</option><option value="PN">Pitcairn</option><option value="PL">Poland</option><option value="PT">Portugal</option><option value="PR">Puerto Rico</option><option value="QA">Qatar</option><option value="RE">Reunion</option><option value="RO">Romania</option><option value="RU">Russian Federation</option><option value="RW">Rwanda</option><option value="KN">Saint Kitts and Nevis</option><option value="LC">Saint LUCIA</option><option value="VC">Saint Vincent and the Grenadines</option><option value="WS">Samoa</option><option value="SM">San Marino</option><option value="ST">Sao Tome and Principe</option><option value="SA">Saudi Arabia</option><option value="SN">Senegal</option><option value="SC">Seychelles</option><option value="SL">Sierra Leone</option><option value="SG">Singapore</option><option value="SK">Slovakia (Slovak Republic)</option><option value="SI">Slovenia</option><option value="SB">Solomon Islands</option><option value="SO">Somalia</option><option value="ZA">South Africa</option><option value="GS">South Georgia and the South Sandwich Islands</option><option value="ES">Spain</option><option value="LK">Sri Lanka</option><option value="SH">St. Helena</option><option value="PM">St. Pierre and Miquelon</option><option value="SD">Sudan</option><option value="SR">Suriname</option><option value="SJ">Svalbard and Jan Mayen Islands</option><option value="SZ">Swaziland</option><option value="SE">Sweden</option><option value="CH">Switzerland</option><option value="SY">Syrian Arab Republic</option><option value="TW">Taiwan, Province of China</option><option value="TJ">Tajikistan</option><option value="TZ">Tanzania, United Republic of</option><option value="TH">Thailand</option><option value="TG">Togo</option><option value="TK">Tokelau</option><option value="TO">Tonga</option><option value="TT">Trinidad and Tobago</option><option value="TN">Tunisia</option><option value="TR">Turkey</option><option value="TM">Turkmenistan</option><option value="TC">Turks and Caicos Islands</option><option value="TV">Tuvalu</option><option value="UG">Uganda</option><option value="UA">Ukraine</option><option value="AE">United Arab Emirates</option><option value="GB">United Kingdom</option><option value="US">United States</option><option value="UM">United States Minor Outlying Islands</option><option value="UY">Uruguay</option><option value="UZ">Uzbekistan</option><option value="VU">Vanuatu</option><option value="VE">Venezuela</option><option value="VN">Viet Nam</option><option value="VG">Virgin Islands (British)</option><option value="VI">Virgin Islands (U.S.)</option><option value="WF">Wallis and Futuna Islands</option><option value="EH">Western Sahara</option><option value="YE">Yemen</option><option value="ZM">Zambia</option><option value="ZW">Zimbabwe</option></select></div>
var handleRegister = function () {function format(state) { if (!state.id) return state.text; // optgroup return "<img class='flag' src='assets/img/flags/" + state.id.toLowerCase() + ".png'/> " + state.text; }$("#select2_sample4").select2({ placeholder: '<i class="fa fa-map-marker"></i> Select a Country', allowClear: true, formatResult: format, formatSelection: format, escapeMarkup: function (m) { return m; } });
- select2 bootstrap 简单使用
- select2 bootstrap 简单使用
- bootstrap与Select2使用小结
- 在BootStrap的modal中使用Select2
- # 关于 \kartik\select2\Select2 在 Bootstrap 模态框内不能使用智能搜索的问题
- JS组件系列——Bootstrap Select2组件使用小结
- JS组件系列——Bootstrap Select2组件使用小结
- select2在bootstrap modal中不能正常使用问题
- bootstrap--table,select2及x-editable的使用小结
- select2使用
- select2使用
- Select2 使用
- select2使用
- select2与Bootstrap冲突解决
- bootstrap select2 动态改变值
- bootstrap select2 动态改变值
- [Ruby On Rails] gem select2 的简单使用
- select2简单使用(含ajax获取是数据)
- Tkinter--Text文本框样例
- Spring security学习笔记三
- 有哪些应用(非游戏)是 cocos2dx开发的
- poj3017 Cut the Sequence 单调队列优化dp 好题!
- Binary Tree Maximum Path Sum
- select2 bootstrap 简单使用
- 励志篇--如何安排自己的时间!!
- Optimal Parking 1673
- 深入理解Linux的软链接和硬链接等Linux易漏知识
- iOS程序-UIButton和UIImageView的区别
- 每日总结-05-14
- Learn Beautiful Soup(2)——BeautifulSoup的对象
- PLSQL执行sql的几种方法
- 学习总结之 Servlet入门知识 处理Response