Textarea autosize
Overview
Autosize is a small, stand-alone script to automatically adjust textarea height to fit text. Use CSS to specify amin-height
and max-height
for the textarea element. Once the height exceeds the max-height
, autosize will re-enable the vertical scrollbar.The rows attribute can also be used to specify a minimum height. The rows attribute has a default value of 2, so to make the textarea smaller than that you'll need to set the value to 1. Example:
<textarea rows='1'></textarea>
.
Usage
The autosize function accepts a single textarea element, or an array or array-like object (such as a NodeList or jQuery collection) of textarea elements:
// From a NodeList
autosize(document.querySelectorAll('textarea'));
// from a single Node
autosize(document.querySelector('textarea'));
// from a jQuery collection
autosize($('textarea'));
Life-cycle events
Event | Description |
---|---|
autosize:update |
Once you've assigned autosize to an element, you can manually trigger the resize event by using the 'autosize:update' event. Autosize has no way of knowing when a script has changed the value of a textarea element, or when the textarea element styles have changed, so this event would be used instruct autosize to resize the textarea
|
autosize:autosize:destroy |
|
autosize:resized |
This event is fired every time autosize adjusts the textarea height.
If you are using jQuery, you can use the on/off methods to listen to this event:
|
Methods
These methods are provided as an alternative to using the life-cycle events
Method | Description |
---|---|
autosize.update(elements) |
For manually recalculating the height for a textarea element, array, or array-like object
|
autosize.destroy(elements) |
Removes autosize and reverts it's changes from a textarea element, array, or array-like object
|
Dual listbox
Overview
Bootstrap Dual Listbox is a responsive dependency-free dual listbox widget. It works on all modern browsers and on touch devices. The dual listbox is created from a regular multiple select by callingnew DualListbox(listboxBasicElement, options);
on a selector. Although this component has no dependency, its styles are based on Bootstrap framework to match the global look and feel.
Usage
Load JavaScript library or include it in the bundle:
<!-- CDN -->
<script src="https://cdn.jsdelivr.net/npm/dual-listbox/dist/dual-listbox.min.js"></script>
<!-- Load plugin -->
<script src="assets/js/vendor/forms/inputs/duallistbox.min.js"></script>
Then initialize via JavaScript:
let dualListbox = new DualListbox("select"); // Selects the first selectbox on the page.
let dualListbox = new DualListbox(".select"); // Selects the first element with the class 'select'
let dualListbox = new DualListbox("#select"); // Selects the first element with the id 'select'
let select = document.querySelector("#select");
let dualListbox = new DualListbox(select); // Add a HTMLElement
You can also pass some options to the DualListbox:
let dualListbox = new DualListbox("#select", {
addEvent: function (value) {
// Should use the event listeners
console.log(value);
},
removeEvent: function (value) {
// Should use the event listeners
console.log(value);
},
availableTitle: "Different title",
selectedTitle: "Different title",
addButtonText: ">",
removeButtonText: "<",
addAllButtonText: ">>",
removeAllButtonText: "<<",
sortable: true,
upButtonText: "ᐱ",
downButtonText: "ᐯ",
draggable: true,
options: [
{ text: "Option 1", value: "OPTION1" },
{ text: "Option 2", value: "OPTION2" },
{ text: "Selected option", value: "OPTION3", selected: true },
],
});
dualListbox.addEventListener("added", function (event) {
console.log(event);
console.log(event.addedElement);
});
dualListbox.addEventListener("removed", function (event) {
console.log(event);
console.log(event.removedElement);
});
Options
When calling $("#element").bootstrapDualListbox()
you can pass a parameters object with zero or more of the following:
Option | Default | Excepted values | Explanation |
---|---|---|---|
draggable | true |
boolean |
If the list items should be draggable. |
showSortButtons | false |
boolean |
If the sort buttons should be shown. (up and down) |
enableDoubleClick | true |
boolean |
If double clicking a list items should change column. |
showAddButton | true |
boolean |
If the "add" button should be shown. |
showRemoveButton | true |
boolean |
If the "remove" button should be shown. |
showAddAllButton | true |
boolean |
If the "add all" button should be shown. |
showRemoveAllButton | true |
boolean |
If the "remove all" button should be shown. |
availableTitle | "Available options" |
string |
The title that should be shown above the "Available options" |
selectedTitle | "Selected options" |
string |
The title that should be shown above the "Selected options" |
addButtonText | "add" |
string |
The text that should be displayed in the "add" button. |
removeButtonText | "remove" |
string |
The text that should be displayed in the "remove" button. |
addAllButtonText | "add all" |
string |
The text that should be displayed in the "add all" button. |
removeAllButtonText | "remove all" |
string |
The text that should be displayed in the "remove all" button. |
searchPlaceholder | "Search" |
string |
The text that should be displayed in the "search" fields. |
upButtonText | "up" |
string |
The text that should be displayed in the "up" button. (only when sorting is enabled) |
downButtonText | "down" |
string |
The text that should be displayed in the "down" button. (only when sorting is enabled) |
options |
undefined
|
Array<{text:"text to display", value: "what
the select value should be", selected:
false, order: 1}>
|
A list of options that should be added. This will overwrite the select options |
sortFunction |
Function
|
Function |
A function to overwrite the default sorting that will be applied. |
Methods
You can modify the behavior and aspect of the dual listbox by calling its methods, all of which accept a value
and a refresh
option. The value
determines the new parameter value, while refresh
(optional, defaults to false
) tells whether to update the plugin UI or not.
Note: when making multiple chained calls to the plugin, set refresh
to true
to the last call only, in order to make a unique UI change; alternatively, you can also call the refresh
method as your last one.
To call methods on the dual listbox instance, use the following syntax:
// Syntax
$(selector).bootstrapDualListbox(methodName, parameter);
Here are the available methods:
Function name | Arguments | Explanation |
---|---|---|
changeOrder | liItem, newPosition | Change the order of the given list Element and the new position |
addOptions | options | Add a single option to the options list. |
addOption | option, index (optional) | Add a single option to the options list. Optionally add the index. |
addEventListener | eventName, callback | Add an eventListener |
changeSelected | listItem | Change the selected state of the list element. |
actionAllSelected | event (optional) | Change all items to be selected. |
actionAllDeselected | event (optional) | Change all items to not be selected. |
redraw | Redraw the lists. |
Masked inputs
Overview
A very light-weight vanilla JavaScript library that helps format input text content automatically. An inputmask helps the user with the input by ensuring a predefined format. This can be useful for dates, numerics, phone numbers. This library has no dependencies and works great on touch devices. Core features:
- get and set value and unmasked value easily
- no external dependencies
- supports overwrite mode
- supports all major browsers
- supports web components
- supports contenteditable
- RegExp mask
- Function mask
- Number mask (integer and decimal support)
- Date mask (with various format support and autofix mode)
- Dynamic/on-the-fly mask
- Pattern mask
- show placeholder always or when needed
- unmasked value can contain fixed parts
- optional input parts
- custom definitions
- reusable blocks
- Enum and Range masks
- convert and format values with pipe
Usage
Load JavaScript file locally or from CDN:
<!-- CDN -->
<script src="https://unpkg.com/imask"></script>
<!-- Load plugin -->
<script src="assets/js/plugins/forms/inputs/imask.min.js"></script>
Then initialize via JavaScript:
// Initialize
var element = document.getElementById('selector');
var maskOptions = {
mask: '+{7}(000)000-00-00'
};
var mask = IMask(element, maskOptions);
Options
IMask consists of two independent layers: model and view. Model layer contains all masking facilities which can be used independently without UI.
View layer is a glue between UI element and model, it connects listeners and controls changes in both directions.
Input processing is based on a simple idea of comparing states before and after change. State before change is obtained on keydown and on input actual processing takes place. In order to support older browsers manually call _saveSelection to save state and _onInput to handle changes. Pull requests for the beauty are welcomed.
Currently, view layer contains only one component InputMask which supports HTML input-like API. Instance of InputMask is returned when IMask constructor is called.To create new mask on element use:
var mask = IMask(element, maskOptions);
Get/set value and unmasked value:
mask.value = "+7(999)999-99-99";
console.log(mask.value); // "+7(999)999-99-99"
console.log(mask.unmaskedValue); // "79999999999"
mask.unmaskedValue = "70000000000";
console.log(mask.value); // "+7(000)000-00-00"
console.log(mask.unmaskedValue); // "70000000000"
For typed masks like Number
or Date
it is possible to work with typed values. For untyped masks typedValue
and unmaskedValue
works identically.
mask.updateOptions({mask: Number});
mask.typedValue = 100; // use number
console.log(mask.value); // "100"
console.log(mask.unmaskedValue); // "100"
console.log(mask.typedValue); // 100
Update options:
mask.updateOptions({
mask: Number,
min: 0,
max: 100
}); // also updates UI
Clean and destroy:
mask.destroy();
Listen to events:
// 'accept' event fired on input when mask value has changed
function log () {console.log(mask.value)};
mask.on("accept", log);
// 'complete' event fired when the value is completely filled
// Note: this makes sense only for Pattern-based masks
mask.on("complete", function () {console.log(mask.value)});
Stop listening to events:
mask.off("accept", log);
// omit handler argument to unbind all handlers
mask.off("complete");
Get Masked model:
var masked = mask.masked;
masked.reset(); // UI will NOT be updated
Bootstrap maxlength
Overview
This plugin integrates by default with Twitter bootstrap using badges to display the maximum length of the field where the user is inserting text. This plugin uses the HTML5 attributemaxlength
to work. The indicator badge shows up on focusing on the element, and disappears when the focus is lost.
Usage
First you need to load jQuery library as Bootstrap maxlength plugin is jQuery dependent. Then add a path to the plugin file:
<!-- Load jQuery -->
<script src="assets/js/jquery/jquery.min.js"></script>
<!-- Load plugin -->
<script src="assets/js/plugins/forms/inputs/maxlength.min.js"></script>
Then initialize via JavaScript:
// Initialize
$('input[maxlength]').maxlength({
// options
});
Options
Option | Default | Description |
---|---|---|
alwaysShow |
false | If true the threshold will be ignored and the remaining length indication will be always showing up while typing or on focus on the input |
threshold |
10 | This is a number indicating how many chars are left to start displaying the indications |
warningClass |
badge badge-success | It's the class of the element with the indicator. By default is the bootstrap badge badge-success but can be changed to anything you'd like |
limitReachedClass |
badge badge-danger | It's the class the element gets when the limit is reached |
separator |
'/' | Represents the separator between the number of typed chars and total number of available chars |
preText |
'' | String of text that can be outputted in front of the indicator |
postText |
'' | String outputted after the indicator |
showMaxLength |
true | If false , will display just the number of typed characters, e.g. will not display the max length |
showCharsTyped |
true | If false , will display just the remaining length, e.g. will display remaining lenght instead of number of typed characters |
placement |
'bottom' | String, define where to output the counter. Possible values are: bottom, left, top, right, bottom-right, top-right, top-left, bottom-left and centered-right |
appendToParent |
'' | Appends the maxlength indicator badge to the parent of the input rather than to the body |
message |
'' | An alternative way to provide the message text, i.e. 'You have typed %charsTyped% chars, %charsRemaining% of %charsTotal% remaining'. %charsTyped%, %charsRemaining% and %charsTotal% will be replaced by the actual values. This overrides the options separator , preText , postText and showMaxLength . Alternatively you may supply a function that the current text and max length and returns the string to be displayed |
utf8 |
false | If true the input will count using utf8 bytesize/encoding. For example: the '£' character is counted as two characters |
twoCharLinebreak |
'' | Count linebreak as 2 characters to match IE/Chrome textarea validation |
customMaxAttribute |
'' | Allows a custom attribute to display indicator without triggering native maxlength behaviour. Ignored if value greater than a native maxlength attribute. 'overmax' class gets added when exceeded to allow user to implement form validation |
placement |
this |
String, object, or function, to define where to output the counter.
|
Events
Event | Description |
---|---|
maxlength.reposition |
On an input element triggers re-placing of its indicator. Useful if textareas are resized by an external trigger |
maxlength.shown |
Triggered when the indicator is displayed |
maxlength.hidden |
Triggered when the indicator is removed from view |
Passy
Overview
You cant emphasize the importance of good passwords. Passy plugin was created to make it easier for developers to give good feedback on a password. Passy is a jQuery plugin to rate and generate passwords.Usage
First you need to load jQuery library as Passy plugin is jQuery dependent. Then add a path to the plugin file:
<!-- Load jQuery -->
<script src="assets/js/jquery/jquery.min.js"></script>
<!-- Load plugin -->
<script src="assets/js/vendor/forms/inputs/passy.js"></script>
Then initialize via JavaScript:
// Initialization example
$('input').passy(function( strength, valid ) {
// Set color based on validness and strength
if(valid) {
if( strength < $.passy.strength.HIGH) {
color = 'orange';
} else {
color = 'green';
}
} else {
color = 'red';
}
$(this).css('background-color', color);
});
Configuration
Before calling .passy(), you can alter these settings:
// Requirements a inserted password should meet
$.passy.requirements = {
// Character types a password should contain
characters: [
$.passy.character.DIGIT,
$.passy.character.LOWERCASE,
$.passy.character.UPPERCASE,
$.passy.character.PUNCTUATION
],
// A minimum and maximum length
length: {
min: 8,
max: Infinity
}
};
// Thresholds are numeric values representing
// the estimated amount of days for a single computer
// to brute force the password, assuming it processes
// about 1,000,000 passwords per second
$.passy.threshold = {
medium: 365,
high: Math.pow( 365, 2 ),
extreme: Math.pow( 365, 5 )
};
Methods
Generate a password of a specific length:
// 'Generate method'
$('input').passy('generate', 16);
Check if a field’s content is valid:
// 'Valid' method
if (
$('input').passy('valid')
)
{ ... }
Autocomplete
Overview
autoComplete.js is a simple, pure vanilla Javascript library progressively designed for speed, high versatility, and seamless integration with a wide range of projects & systems
Main features:
- Pure Vanilla Javascript
- Zero Dependencies
- Simple & Lightweight
- Powerful Search Engine with two different modes
- Diacritics Support
- Debounce Support
- Life Cycle Events
- Useful plugin API
- WAI-ARIA Compliant
- Highly Customizable
- Works on anything (
<input>
,<textarea>
andcontentEditable
elements) - Well Documented
Usage
Load JavaScript file locally or from CDN:
<!-- CDN -->
<script src="https://cdnjs.cloudflare.com/ajax/libs/tarekraafat-autocomplete.js/10.2.7/autoComplete.min.js"></script>
<!-- Load library -->
<script src="assets/js/vendor/forms/inputs/autocomplete.min.js"></script>
Create element:
<!-- Autocomplete element -->
<input type="search" class="form-control" id="autocomplete_basic" autocomplete="new-search" placeholder="Search country">
Then initialize via JavaScript:
const autocompleteBasic = new autoComplete({
selector: "#autocomplete_basic",
data: {
src: autocompleteData
},
resultItem: {
highlight: true
},
events: {
input: {
selection: function(event){
const selection = event.detail.selection.value;
autocompleteBasic.input.value = selection;
}
}
}
});
Autocomplete options
Option | Default | Description |
---|---|---|
name |
autoComplete | Responsible for the global instance naming where all elements inherit their class & id names |
selector |
#autoComplete | Responsible for the input, textarea, or contentEditable element selection |
wrapper |
true | Responsible for rendering the div that wraps the input and the list element |
data |
... | Responsible for the data source selection |
data.source |
null | Data source |
data.keys |
null | Data keys (required) |
data.cache |
false | Enables caching |
data.filter |
No action | Data filtering |
trigger |
if input field NOT empty and greater than or equal threshold | Responsible for Event & Condition rules that trigger autoComplete.js engine to start |
query |
Returns raw input value | Responsible for Query interception & manipulation |
placeholder |
Blank/Empty | Responsible for the input field placeholder value setting |
threshold |
1 | Responsible for setting threshold value of the minimum characters length where autoComplete.js engine starts |
debounce |
0 | Responsible for setting delay time duration that counts after typing is done for autoComplete.js engine to start |
searchEngine |
"strict" | Responsible for setting the Search engine Type/Mode or custom engine |
diacritics |
false | Responsible for turning on/off language diacritics supported search |
resultsList |
... | Responsible for the results list element rendering, interception, and customizing |
resultsList.tag |
ul | List tag |
resultsList.id |
autoComplete_list_[id] | List id |
resultsList.class |
null | For overriding the default class names used |
resultsList.destination |
#autoComplete | Destination selector |
resultsList.position |
afterend | List position |
resultsList.element |
function | List element |
resultsList.maxResults |
5 | Maximum number of results |
resultsList.tabSelect |
false | enable/disable tab selection |
resultsList.noResults |
false | enable/disable list resistance in case of no results |
resultItem |
... | Responsible for the result item element rendering, interception, and customizing |
resultItem.tag |
li | List item tag |
resultItem.id |
autoComplete_result_[index] | List item ID |
resultItem.class |
null | List item class |
resultItem.element |
Function | List item element |
resultItem.highlight |
false | Enable/disable list item highlight |
resultItem.selected |
null | Selected class |
submit |
false | Responsible for the Enter button default behavior |
events |
input / list | Responsible for the input field and results list events additions or overriding |
Autocomplete API
init()
init()
core function which is responsible for the following tasks in order:
- Setting
input
field attributes &placeholder
text (if set) - Creating
wrapper
element and moving the selectedinput
inside it - Creating new empty hidden
list
- Getting
data
if set tocache
- Attaching all event listeners on the
events
list - Emitting
init
event
autoCompleteJS.init();
start(query)
start(query)
core function which is responsible for the following tasks in order::
- Getting the
input
query value if NOT passed as an argument - Manipulating
query
value - Checking
trigger
condition validity to proceed - Fetching
data
fromsrc
orstore
if cached - Start matching results
- Rendering
list
if enabled
autoCompleteJS.start("tea");
search(query, record, options)
autoComplete.js powerful search engine:
autoCompleteJS.search(query, record, options);
// Or
autoComplete.search(query, record, options)
open()
Opens resultsList
if not empty
autoCompleteJS.open();
next()
Navigates to the next resultItem
on the list
autoCompleteJS.next();
previous()
Navigates to the previous resultItem
on the list
autoCompleteJS.previous();
goTo(index)
Navigates to a specific resultItem
on the list by its index
number
autoCompleteJS.goTo(1);
select(index)
Selects a resultItem
from the list by its index
number
autoCompleteJS.select(1);
close()
Closes the resultsList
if opened
autoCompleteJS.close();
unInit()
Removes all the event listeners on the events
list
autoCompleteJS.unInit();
Autocomplete events
init
Fires after autoComplete.js
engine is initialized and ready
document.querySelector("#autoComplete").addEventListener("init", function (event) {
// "event.detail" carries the returned data values
console.log(event);
});
response
Fires after fetching the data
is completed and the data
is ready
document.querySelector("#autoComplete").addEventListener("response", function (event) {
// "event.detail" carries the returned data values
console.log(event.detail);
});
results
Fires after the search
operation is done and matching results are ready
document.querySelector("#autoComplete").addEventListener("results", function (event) {
// "event.detail" carries the matching results values
console.log(event.detail);
});
open
Fires after the results list is opened
document.querySelector("#autoComplete").addEventListener("open", function (event) {
// "event.detail" carries the autoComplete.js "feedback" object
console.log(event.detail);
});
navigate
Fires on every "resultsList" navigation interaction
document.querySelector("#autoComplete").addEventListener("navigate", function (event) {
// "event.detail" carries the autoComplete.js "feedback" object
console.log(event.detail);
});
selection
Fires on result item selection
document.querySelector("#autoComplete").addEventListener("selection", function (event) {
// "event.detail" carries the autoComplete.js "feedback" object
console.log(event.detail);
});
close
Fires after "resultsList" is closed
document.querySelector("#autoComplete").addEventListener("close", function (event) {
// "event.detail" carries the autoComplete.js "feedback" object
console.log(event.detail);
});
Form validation
Overview
This jQuery plugin makes simple clientside form validation easy, whilst still offering plenty of customization options. It makes a good choice if you’re building something new from scratch, but also when you’re trying to integrate something into an existing application with lots of existing markup.
The plugin comes bundled with a useful set of validation methods, including URL and email validation, while providing an API to write your own methods. All bundled methods come with default error messages in english and translations into 37 other languagesUsage
Include the following lines of code in the <head>
section of your HTML:
<!-- Load jQuery -->
<script src="assets/js/jquery/jquery.min.js"></script>
<!-- Load plugin -->
<script src="assets/js/plugins/forms/validation/validate.min.js"></script>
Select a form to validate and call the validate method:
<!-- Create form -->
<form class="validate" id="commentForm" method="get" action="">
<fieldset>
<legend>Please provide your name, email address (won't be published) and a comment</legend>
<p>
<label for="cname">Name (required, at least 2 characters)</label>
<input id="cname" name="name" minlength="2" type="text" required>
</p>
</fieldset>
</form>
Finally call the plugin via JavaScript:
// Basic initialization
$("#commentForm").validate({
// options
});
Validate options
Name | Default | Description |
---|---|---|
debug |
false | Enables debug mode. If true, the form is not submitted and certain errors are displayed on the console (will check if a window.console property exists). Try to enable when a form is just submitted instead of validation stopping the submit |
submitHandler |
native form submit | Callback for handling the actual submit when the form is valid. Gets the form as the only argument. Replaces the default submit. The right place to submit a form via Ajax after it is validated |
invalidHandler |
{} | Callback for custom code when an invalid form is submitted. Called with an event object as the first argument, and the validator as the second |
ignore |
":hidden" | Elements to ignore when validating, simply filtering them out. jQuery's not-method is used, therefore everything that is accepted by not() can be passed as this option. Inputs of type submit and reset are always ignored, so are disabled elements |
rules |
read from markup (classes, attributes, data) | Key/value pairs defining custom rules. Key is the name of an element (or a group of checkboxes/radio buttons), value is an object consisting of rule/parameter pairs or a plain String . Can be combined with class/attribute/data rules. Each rule can be specified as having a depends-property to apply the rule only in certain conditions |
messages |
Default message for the method used | Key/value pairs defining custom messages. Key is the name of an element, value the message to display for that element. Instead of a plain message, another map with specific messages for each rule can be used. Overrides the title attribute of an element or the default message for the method (in that order). Each message can be a String or a Callback . The callback is called in the scope of the validator, with the rule's parameters as the first argument and the element as the second, and must return a String to display as the message |
groups |
[] | Specify grouping of error messages. A group consists of an arbitrary group name as the key and a space separated list of element names as the value. Use errorPlacement to control where the group message is placed |
onsubmit |
true | Validate the form on submit. Set to false to use only other events for validation. Set to a Function to decide for yourself when to run validation. A boolean true is not a valid value |
onfocusout |
{} | Validate elements (except checkboxes/radio buttons) on blur . If nothing is entered, all rules are skipped, except when the field was already marked as invalid. Set to a Function to decide for yourself when to run validation. A boolean true is not a valid value |
onkeyup |
{} | Validate elements on keyup . As long as the field is not marked as invalid, nothing happens. Otherwise, all rules are checked on each key up event. Set to false to disable. Set to a Function to decide for yourself when to run validation. A boolean true is not a valid value |
onclick |
{} | Validate checkboxes and radio buttons on click . Set to false to disable. Set to a Function to decide for yourself when to run validation. A boolean true is not a valid value |
focusInvalid |
true | Focus the last active or first invalid element on submit via validator.focusInvalid() . The last active element is the one that had focus when the form was submitted, avoiding stealing its focus. If there was no element focused, the first one in the form gets it, unless this option is turned off |
focusCleanup |
false | If enabled, removes the errorClass from the invalid elements and hides all error messages whenever the element is focused. Avoid combination with focusInvalid |
errorClass |
'error' | Use this class to create error labels, to look for existing error labels and to add it to invalid elements |
validClass |
'valid' | This class is added to an element after it was validated and considered valid |
errorElement |
'label' | Use this element type to create error messages and to look for existing error messages. The default, "label" , has the advantage of creating a meaningful link between error message and invalid field using the for attribute (which is always used, regardless of element type) |
wrapper |
'window' | Wrap error labels with the specified element. Useful in combination with errorLabelContainer to create a list of error messages |
errorLabelContainer |
- | Hide and show this container when validating |
errorContainer |
- | Hide and show this container when validating |
showErrors |
{} | A custom message display handler. Gets the map of errors as the first argument and an array of errors as the second, called in the context of the validator object. The arguments contain only those elements currently validated, which can be a single element when doing validation onblur/keyup. You can trigger (in addition to your own messages) the default behaviour by calling this.defaultShowErrors() |
errorPlacement |
After the invalid element | Customize placement of created error labels. First argument: The created error label as a jQuery object. Second argument: The invalid element as a jQuery object |
success |
- | If specified, the error label is displayed to show a valid element. If a String is given, it is added as a class to the label. If a Function is given, it is called with the label (as a jQuery object) and the validated input (as a DOM element). The label can be used to add a text like "ok!" |
highlight |
Adds errorClass to the element | How to highlight invalid fields. Override to decide which fields and how to highlight |
unhighlight |
Removes the errorClass | Called to revert changes made by option highlight , same arguments as highlight |
ignoreTitle |
false | Set to skip reading messages from the title attribute, helps to avoid issues with Google Toolbar; default is false for compability, the message-from-title is likely to be completely removed in a future release |
Plugin methods
This library adds three jQuery plugin methods, the main entry point being the validate
method:
Method | Description |
---|---|
validate() |
Validates the selected form |
valid() |
Checks whether the selected form or selected elements are valid |
rules() |
Read, add and remove rules for an element |
Custom selectors
This library also extends jQuery with three custom selectors:
Method | Description |
---|---|
:blank |
Selects all elements with a blank value |
:filled |
Selects all elements with a filled value |
:unchecked |
Selects all elements that are unchecked |
Validator
The validate method returns a Validator object that has a few public methods that you can use to trigger validation programmatically or change the contents of the form. The validator object has more methods, but only those documented here are intended for usage.
Method | Description |
---|---|
Validator.form() |
Validates the form |
Validator.element() |
Validates a single element |
Validator.resetForm() |
Resets the controlled form |
Validator.showErrors() |
Show the specified messages |
Validator.numberOfInvalids() |
Returns the number of invalid fields |
jQuery.validator.addMethod() |
Add a custom validation method |
jQuery.validator.format() |
Replaces {n} placeholders with arguments |
jQuery.validator.setDefaults() |
Modify default settings for validation |
jQuery.validator.addClassRules() |
Add a compound class method |
Built-in Validation methods
A set of standard validation methods is provided:
Method | Description |
---|---|
required |
Makes the element required |
remote |
Requests a resource to check the element for validity |
minlength |
Makes the element require a given minimum length |
maxlength |
Makes the element require a given maxmimum length |
rangelength |
Makes the element require a given value range |
min |
Makes the element require a given minimum |
max |
Makes the element require a given maximum |
range |
Makes the element require a given value range |
email |
Makes the element require a valid email |
url |
Makes the element require a valid url |
date |
Makes the element require a date |
dateISO |
Makes the element require an ISO date |
number |
Makes the element require a decimal number |
digits |
Makes the element require digits only |
creditcard |
Makes the element require a credit card number |
equalTo |
Requires the element to be the same as another one |
Some more methods are provided as add-ons, and are currently included in additional-methods.js in the download package. Not all of them are documented here:
Method | Description |
---|---|
accept |
Makes a file upload accept only specified mime-types |
extension |
Makes the element require a certain file extension |
phoneUS |
Validate for valid US phone number |
require_from_group |
Ensures a given number of fields in a group are complete |
Tokenfield
Overview
Input field with tagging/token/chip capabilities written in raw JavaScript. Tokens in OS X or Chips in Android - small UI elements which are inserted into various input fields that often combine with autocomplete functionality.
Tokens allow designers to display extra information about input. For example, in email applications when typing an email address of the recipient, input field could display full name of the owner of a given email and a his/her picture.
This Tokenfield implementation is written in raw JavaScript without any extra dependencies like jQuery. it has one somewhat opinionated behavior - Tokenfield intended use case is work with structured data. More specifically, it expects autocomplete data to be JSOn formatted array of objects where each object contains token ID and token NameUsage
Load JavaScript file locally or from CDN:
<!-- Load plugin -->
<script src="assets/js/vendor/forms/tags/tokenfield.min.js"></script>
Create an HTML element:
<!-- Create element -->
<input type="text" class="form-control tokenfield-basic" placeholder="Select car brand">
Finally call the plugin via JavaScript:
// Basic initialization
document.querySelectorAll('.tokenfield-basic').forEach(function(element) {
const tfBasic = new Tokenfield({
el: element,
items: cars
});
});
Plugin options
Options for individual tokenfields can alternatively be specified through the use of data attributes, as explained below:
Name | Type | Default | Description |
---|---|---|---|
el | string or DOM node | null | DOM element or string with selector pointing at an element you want to turn into tokenfield. |
form | bool, string or DOM node | true | Listens to reset event on the specified form. If set to true listens to immediate parent form. |
items | array | [] | Array of objects amongst which autocomplete will try to find a match. Default format might look like this: [{id: 1, name: 'foo'}, {id: 2, name: 'bar'}] |
setItems | array | [] | Array of objects which would be displayed as selected after Tokenfield has been created. |
newItems | bool | true | Option to allow user to add custom tokens instead of using preset list of tokens or tokens retrieved from the server. |
multiple | bool | true | Option to allow multiple tokens in the field. |
maxItems | integer | 0 | Option to limit number of items. Set to 0 to remove the limit. |
matchRegex | string | '{value}' |
Regex string that would be used for matching - when regex is compiled {value} would be replaced with escaped user input. |
matchFlags | string | 'i' |
Regex flags used in matching. Default is i - case insensitive matching. |
matchStart | bool | false |
Option to do matching only from the beginning of the string - it compiles match regex to basicall this format: /^{value}/i . |
matchEnd | bool | false |
Option to do matching only from the end of the string - it compiles match regex to basicall this format: /{value}$/i . |
remote | object | Details on that - below in Autocomplete section. | |
addItemOnBlur | bool | false |
If set to true, will add new item to the tokenfield on input blur. Either sets new item or first match from suggested list. |
delimiters | array | [] | Option to specify certain characters/sets of characters to be used as delimiters during tokenization or input events on tokenfield. |
addItemsOnPaste | bool | false |
If set to true, will add new item to the tokenfield on paste. Tokenization happens using delimiters options listed above. |
placeholder | null or string | null | Set a placeholder that will be shown in the input. If set to null, will try to use placeholder attribute from the original element set in el |
inputType | string | 'text' |
Specifies HTML type attribute for the input element. |
minChars | integer | 2 | Specifies how many characters user has to input before autocomplete suggester is shown. |
maxSuggest | integer | 10 | Specifies how many suggestions should be shown. |
filterSetItems | bool | true |
Specifies whether already set items should not be shown in suggested list. |
filterMatchCase | bool | false |
Used to match set items and new item by case-sensitivity. By default is set to false and does not take case of item value into the account. |
itemLabel | string | 'name' |
Property of an item object which is used to display text in tokens. |
itemName | string | 'items' |
Each token item will have its own hidden input which will contain an ID of a given item and a name attribute in an array format. This option sets a name. By default it is set to "items" which means that when user will submit a form server would receive an array of IDs under the name "items". |
newItemName | string | 'items_new' |
Same as the above except it is only related to new items which were not added via autocomplete. |
itemValue | string | 'id' |
Specifies which property from the autocomplete data to use as a primary identifying value. |
itemData | string | 'name' |
Which property should be used when you do autocomplete on a given array of items. |
validateNewItem | closure | null |
If set, closure will run on every attempt to add new non-existing item to validate it. Return true to allow an item, return any falsy value and it will prevent new item from being added. |
Remote options
Below you will find list of options which are related to remote autocomplete requests. Options are set as properties of an object assigned to remote property of the parent options object:
new Tokenfield({
remote: {
url: "http://example.com",
...
}
});
Name | Type | Default | Description |
---|---|---|---|
type | string | 'GET' |
Sets AJAX request type. Usually GET or POST |
url | string | null | Specifies which URL will be used to retrieve autocomplete data. If set to null - remote autocomplete won't be performed. |
queryParam | string | 'q' |
Sets name of the parameter which would contain value that user typed in the input field. |
delay | integer | 300 | Sets delay in milliseconds after which remote request is performed. |
timestampParam | string | 't' |
Sets parameter for the timestamp when remote call was requested. |
params | object | {} |
Sets any additional AJAX params |
headers | object | {} |
Sets AJAX headers. Could be simple key:value items, or key:function items if you want to add headers dynamically |
Events
EventEmitter
and therefore supports such event as: 'on'
, 'once'
, 'removeAllListeners'
, 'removeListener'
. Available events are:
Event Type | Description |
---|---|
change | Fired after any change in tokens list - after adding or removing tokens, setting multiple tokens manually etc. |
showSuggestions | Fired before Tokenfield would show suggestions box. |
shownSuggestions | Fired after Tokenfield has shown suggestions box. |
hideSuggestions | Fired before Tokenfield would hide suggestions box. |
hiddenSuggestions | Fired after Tokenfield has hidden suggestions box. |
addToken | Fired before token has been added to the tokenfield. Second argument contains token data. |
addedToken | Fired after token has been added to internal token list. |
removeToken | Fired before token has been removed from the tokenfield. Second argument contains token data. |
removedToken | Fired after token has been removed from the tokenfield. Second argument contains removed token data. |
Methods
Method name | Description |
---|---|
remapData | Fired on every data request. Override it if you want to change structure of an available data - change props names, sanitize property values, remove props. Just make sure to return array of objects which would be consumed by the tokenfield instance. |
renderSetItemLabel | Fired on token item render. Override this method in order to change how label for each token is rendered |
onInput | Fired when you type something in the input field. Accepts value of the input field and event object. |
showSuggestions | Shows list of suggested items if there are any. |
hideSuggestions | Temporarily hides list of suggested items. |
getItems | Returns an array containing objects for currently set tokens. |
setItems | Override current set tokens with your own array of tokens. Input could be array or a single object and must conform to the format described at the beginning of the readme. |
addItems | Add tokens. Input could be an array or a single object. Object or array of objects must conform to the correct format described at the beinning of readme. |
sortItems | Updates internal state of the set tokens based on the HTML state of the tokens - useful when you apply a "sortable" or "draggable" library on tokenfield items. |
removeItem(value) | Remove an item based on the given input. Input could be an item object, item name for new item or item id for existing item. |
emptyItems | Remove all currently set token items. |
getSuggestedItems | Returns an array of suggested items. |
focus | Focus the tokenfield. |
blur | Remove focus from the tokenfield. |
remove | Destroy tokenfield and display original element it was attached to. |