Bootstrap tokenfield 使用指南
2016-07-25 15:26
691 查看
Tokenfield v0.12.1
Examples
Create elegant taggable fields with copy/paste and keyboard support.Using jQuery UI Autocomplete
red×
green×
blue×
<input type="text" class="form-control" id="tokenfield" value="red,green,blue" />
$('#tokenfield').tokenfield({ autocomplete: { source: ['red','blue','green','yellow','violet','brown','purple','black','white'], delay: 100 }, showAutocompleteOnFocus: true })
Using Twitter Typeahead
red×
green×
blue×
<input type="text" class="form-control" id="tokenfield-typeahead" value="red,green,blue" />
var engine = new Bloodhound({ local: [{value: 'red'}, {value: 'blue'}, {value: 'green'} , {value: 'yellow'}, {value: 'violet'}, {value: 'brown'}, {value: 'purple'}, {value: 'black'}, {value: 'white'}], datumTokenizer: function(d) { return Bloodhound.tokenizers.whitespace(d.value); }, queryTokenizer: Bloodhound.tokenizers.whitespace }); engine.initialize(); $('#tokenfield-typeahead').tokenfield({ typeahead: [null, { source: engine.ttAdapter() }] });
Usage
Trigger tokenfield via JavaScript:
$('.tokenfield').tokenfield()
Options
Options can be passed via data attributes or JavaScript. For data attributes, append the option name to data-,
as in
data-minLength="".
Name | type | default | description |
---|---|---|---|
tokens | string, array | [] | Tokens (or tags). Can be a string with comma-separated values ("one,two,three"), an array of strings ( ["one","two","three"]), or an array of objects ( [{ value: "one", label: "Einz" }, { value: "two", label: "Zwei" }]) |
limit | int | 0 | Maximum number of tokens allowed. 0 = unlimited. |
minLength | int | 0 | Minimum length required for token value. |
minWidth | int | 60 | Minimum input field width. In pixels. |
autocomplete | object | {} | jQuery UI Autocomplete options |
showAutocompleteOnFocus | boolean | false | Whether to show autocomplete suggestions menu on focus or not. Works only for jQuery UI Autocomplete, as Typeahead has no support for this kind of behavior. |
typeahead | array | [] | Arguments for Twitter Typeahead. The first argument should be an options hash (or nullif you want to use the defaults). The second argument should be a dataset. You can add multiple datasets: typeahead: [options, dataset1, dataset2] |
createTokensOnBlur | boolean | false | Whether to turn input into tokens when tokenfield loses focus or not. |
delimiter | string, array | ',' | A character or an array of characters that will trigger token creation on keypress event. Defaults to ',' (comma). Note - this does not affect Enter or Tab keys, as they are handled in the keydown event. The first delimiter will be used as a separator when getting the list of tokens or copy-pasting tokens. |
beautify | boolean | true | Whether to insert spaces after each token when getting a comma-separated list of tokens. This affects both value returned bygetTokensList() |
inputType | string | 'text' | HTML type attribute for the token input. This is useful for specifying an HTML5 input type like 'email', 'url'or 'tel'which allows mobile browsers to show a specialized virtual keyboard optimized for different types of input. This only sets the type of the visible token input but does not touch the original input field. So you may set the original input to have type="text"but set this inputType option to 'email'if you only want to take advantage of the email style keyboard on mobile, but don't want to enable HTML5 native email validation on the original hidden input. |
Data attributes for individual tokenfields
Options for individual tokenfields can alternatively be specified through the use of data attributes, as explained above.
Styling Twitter Typeahead
Twitter Typeahead comes with no default styling. Make sure to include tokenfield-typeahead.css onyour page.
Methods
.tokenfield(options)
Initializes an input with a tokenfield.$('#myField').tokenfield();
.tokenfield('setTokens', tokens)
Manually set the tokenfield content (replacing the old content)$('#myField').tokenfield('setTokens', 'blue,red,white'); $('#myField').tokenfield('setTokens', ['blue','red','white']); $('#myField').tokenfield('setTokens', [{ value: "blue", label: "Blau" }, { value: "red", label: "Rot" }]);
.tokenfield('createToken', token)
Manually create a token and append it to the input$('#myField').tokenfield('createToken', 'purple'); $('#myField').tokenfield('createToken', { value: 'violet', label: 'Violet' });
.tokenfield('getTokens', active)
Get an array of tokens from the input. Set activeto true to return
only selected tokens.
$('#myField').tokenfield('getTokens');
.tokenfield('getTokensList', delimiter, beautify, active)
Get a comma-separated list of the tokens from the input. You can use an alternative separator by supplying also a delimiterargument.
Setting
beautifyto false will prevent adding a space after each
token. Set
activeto true to return only selected tokens.
$('#myField').tokenfield('getTokensList'); $('#myField').tokenfield('getTokensList', '; ');
.tokenfield('disable')
Disable tokenfield (just like a normal input field)$('#myField').tokenfield('disable');
.tokenfield('enable')
Enable tokenfield (just like a normal input field)$('#myField').tokenfield('enable');
.tokenfield('readonly')
Make tokenfield a readonly field (just like a normal input field)$('#myField').tokenfield('readonly');
.tokenfield('writeable')
Make tokenfield writeable (just like a normal input field)$('#myField').tokenfield('writeable');
.tokenfield('destroy')
Destroy tokenfield and restore original input$('#myField').tokenfield('destroy');
Accessing original input
Though not recommended, you can access the original input field like so: $('#tokenfield').data('bs.tokenfield').$input
You can also set new options for the autocomplete or typehead objects from the original input above like so:
$('#tokenfield').data('bs.tokenfield').$input.autocomplete({source: new_array})
Events
Tokenfield exposes a few events for hooking into it's functionality.Event | Description |
---|---|
tokenfield:initialize | Fires after Tokenfield has been initialized. |
tokenfield:createtoken | This event fires when a token is all set up to be created, but before it is inserted into the DOM and event listeners are attached. You can use this event to manipulate token value and label by changing the appropriate values of attrsproperty of the event. See below for an example. Calling event.preventDefault()or doing return falsein the event handler will prevent the token from being created. |
tokenfield:createdtoken | This event is fired after the token has been created. Here, attrsproperty of the event is also available, but is basically read-only. You can also get a direct reference to the token DOM object via e.relatedTarget. The example below uses this to set an 'invalid' class on the newly created token if it does not pass validation. |
tokenfield:edittoken | This event is fired just before a token is about to be edited. This allows you to manipluate the input field value before it is created. Again, to do this, manipluate the attrsproperty of the event. Here you can also access the token DOM object with e.relatedTarget. Calling event.preventDefault()or doing return falsein the event handler will prevent the token from being edited. |
tokenfield:editedtoken | This event is fired when a token is ready for being edited. It means that the token has been replaced by an input field. |
tokenfield:removetoken | This event is fired right before a token is removed. Here you can also access the token DOM object withe.relatedTarget. Calling event.preventDefault()or doing return falsein the event handler will prevent the token from being removed. You can access token label and value by checking the attrsproperty of the event. Also, e.relatedTargetis a reference to the token DOM object. |
tokenfield:removedtoken | This event is fired right after a token is removed from the DOM. You can access token label and value by checking the attrsproperty of the event. |
invalidclass
to the token.
When the user starts to edit the token, we merge token value and label together again.
me (me@example.com)×
you@example.com×
not really an email×
$('#tokenfield') .on('tokenfield:createtoken', function (e) { var data = e.attrs.value.split('|') e.attrs.value = data[1] || data[0] e.attrs.label = data[1] ? data[0] + ' (' + data[1] + ')' : data[0] }) .on('tokenfield:createdtoken', function (e) { // Über-simplistic e-mail validation var re = /\S+@\S+\.\S+/ var valid = re.test(e.attrs.value) if (!valid) { $(e.relatedTarget).addClass('invalid') } }) .on('tokenfield:edittoken', function (e) { if (e.attrs.label !== e.attrs.value) { var label = e.attrs.label.split(' (') e.attrs.value = label[0] + '|' + e.attrs.value } }) .on('tokenfield:removedtoken', function (e) { alert('Token removed! Token value was: ' + e.attrs.value) }) .tokenfield()
Keyboard support
Tokenfield includes support for manipulating tokens via keyboard
left, right arrow keys
Arrow keys will move between active tokens. Try it out: click on one of the tokens and press left and right arrow keys
Backspace and delete
You can delete a selected token with backspace or delete keys. Try it out now:
Ctrl + A / Cmd + A, Ctrl + C / Cmd + C, Ctrl + V, Cmd + V
If You have one token selected, you can select all tokens with the keyboard. Then, you can copy the tokens using keyboard. You can also paste tokens to another field.try×
pressing×
backspace×
Copy & paste support
You can copy tokens from a tokenfield and paste them to any other field as comma-separated values. When you paste to another tokenfield, they will become tokens there, aswell!Try it out, copy the following to the field below: violet,yellow,brown
copy×
and×
paste×
Validation states
Tokenfield also supports all the default validation states from BootstrapInput with success
red×
green×
blue×
Input with warning
red×
green×
blue×
Input with error
red×
green×
blue×
Various examples of using tokenfield
Using tokenfield with input groupsTags:
cool×
nice×
great×
red×
green×
blue×
Tags:
red×
green×
blue×
Using tokenfield with input group checkboxes and radio buttons
red×
green×
blue×
red×
green×
blue×
Using tokenfield with buttons in input groups
red×
green×
blue×
Go!
red×
green×
blue×
Action
Using tokenfield with different sizes
red×
green×
blue×
red×
green×
blue×
red×
green×
blue×
@
red×
green×
blue×
@
red×
green×
blue×
@
red×
green×
blue×
Disabled tokenfield
red×
green×
blue×
Disabled fieldset with tokenfield
Tokenfield in inline form
Tags
red×
green×
blue×
Search
Tokenfield in horizontal form
Password
Tags
some×
tags×
Sign in
Tokenfield with fluid and fixed widths (50%, 300px, etc...)
Width: 50% (from stylesheet)
red×
green×
blue×
Width: 300px (from stylesheet)
red×
green×
blue×
Width: 400px (inline)
red×
green×
blue×
Tokenfield with RTL direction
red×
相关文章推荐
- bootstrap初试进度条
- Bootstrap 3.3.4 发布,Web 前端 UI 框架
- angular 指令简述
- 利用ASP.NET MVC+Bootstrap搭建个人博客之修复UEditor编辑时Bug(四)
- 浅析Bootstrap验证控件的使用
- 基于BootStrap Metronic开发框架经验小结【六】对话框及提示框的处理和优化
- Bootstrap教程JS插件弹出框学习笔记分享
- Bootstrap插件全集
- Bootstrap编写一个兼容主流浏览器的受众门户式风格页面
- Bootstrap框架动态生成Web页面文章内目录的方法
- JS组件Bootstrap Table使用实例分享
- bootstrap学习笔记之初识bootstrap
- Bootstrap下拉菜单效果实例代码分享
- Bootstrap表单组件教程详解
- BootStrap学习系列之Bootstrap Typeahead 组件实现百度下拉效果(续)
- Bootstrap每天必学之前端开发框架
- Bootstrap 粘页脚效果
- 第八篇Bootstrap下拉菜单实例代码
- Bootstrap选项卡与Masonry插件的完美结合
- bootstrap-wysiwyg结合ajax实现图片上传实时刷新功能