rename addItemFilterFn (#699)

This commit is contained in:
Konstantin Vyatkin 2019-10-29 13:29:31 -04:00 committed by Josh Johnson
parent 2a03d9be12
commit b080bcda7d
7 changed files with 1019 additions and 608 deletions

View file

@ -92,7 +92,7 @@ will be returned. If you target one element, that instance will be returned.
renderChoiceLimit: -1,
maxItemCount: -1,
addItems: true,
addItemFilterFn: null,
addItemFilter: null,
removeItems: true,
removeItemButton: false,
editItems: false,
@ -370,23 +370,29 @@ Pass an array of objects:
**Usage:** Whether the scroll position should reset after adding an item.
### addItemFilterFn
### addItemFilter
**Type:** `Function` **Default:** `null`
**Type:** `string | RegExp | Function` **Default:** `null`
**Input types affected:** `text`
**Usage:** A filter function that will need to return `true` for a user to successfully add an item.
**Usage:** A RegExp or string (will be passed to RegExp constructor internally) or filter function that will need to return `true` for a user to successfully add an item.
**Example:**
```js
// Only adds items matching the text test
new Choices(element, {
addItemFilterFn: (value) => {
return (value !== 'test');
addItemFilter: (value) => {
return ['orange', 'apple', 'banana'].includes(value);
};
});
// only items ending to `-red`
new Choices(element, {
addItemFilter: '-red$';
});
```
### shouldSort

View file

@ -1,22 +1,49 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no">
<head>
<meta charset="UTF-8" />
<meta
name="viewport"
content="width=device-width,initial-scale=1,user-scalable=no"
/>
<title>Choices</title>
<meta name=description itemprop=description content="A lightweight, configurable select box/text input plugin. Similar to Select2 and Selectize but without the jQuery dependency.">
<link rel="apple-touch-icon" sizes="180x180" href="assets/images/apple-touch-icon.png">
<link rel="icon" type="image/png" href="assets/images/favicon-32x32.png" sizes="32x32">
<link rel="icon" type="image/png" href="assets/images/favicon-16x16.png" sizes="16x16">
<link rel="manifest" href="assets/images/manifest.json">
<link rel="mask-icon" href="assets/images/safari-pinned-tab.svg" color="#00bcd4">
<link rel="shortcut icon" href="assets/images/favicon.ico">
<meta name="msapplication-config" content="/assets/images/browserconfig.xml">
<meta name="theme-color" content="#ffffff">
<meta
name="description"
itemprop="description"
content="A lightweight, configurable select box/text input plugin. Similar to Select2 and Selectize but without the jQuery dependency."
/>
<link
rel="apple-touch-icon"
sizes="180x180"
href="assets/images/apple-touch-icon.png"
/>
<link
rel="icon"
type="image/png"
href="assets/images/favicon-32x32.png"
sizes="32x32"
/>
<link
rel="icon"
type="image/png"
href="assets/images/favicon-16x16.png"
sizes="16x16"
/>
<link rel="manifest" href="assets/images/manifest.json" />
<link
rel="mask-icon"
href="assets/images/safari-pinned-tab.svg"
color="#00bcd4"
/>
<link rel="shortcut icon" href="assets/images/favicon.ico" />
<meta
name="msapplication-config"
content="/assets/images/browserconfig.xml"
/>
<meta name="theme-color" content="#ffffff" />
<!-- Ignore these -->
<link rel="stylesheet" href="assets/styles/base.min.css">
<link rel="stylesheet" href="assets/styles/base.min.css" />
<!-- End ignore these -->
<!-- Optional includes -->
@ -24,67 +51,141 @@
<!-- End optional includes -->
<!-- Choices includes -->
<link rel="stylesheet" href="assets/styles/choices.min.css">
<link rel="stylesheet" href="assets/styles/choices.min.css" />
<script src="assets/scripts/choices.min.js"></script>
<!-- End Choices includes -->
<!--[if lt IE 9]>
<style>
.hidden-ie { display: none; }
.visible-ie { display: block; }
.hidden-ie {
display: none;
}
.visible-ie {
display: block;
}
</style>
<![endif]-->
</head>
</head>
<body>
<body>
<div class="container">
<div class="section">
<a href="https://github.com/jshjohnson/Choices" class="logo">
<img src="assets/images/logo.svg" alt="Choices.js logo" class="logo__img hidden-ie">
<img
src="assets/images/logo.svg"
alt="Choices.js logo"
class="logo__img hidden-ie"
/>
<h1 class="visible-ie">Choices.js</h1>
</a>
<p>Choices.js is a lightweight, configurable select box/text input plugin. Similar to Select2 and Selectize but without
the jQuery dependency.</p>
<p>For all config options, visit the <a href="https://github.com/jshjohnson/Choices">GitHub repo</a>.</p>
<hr>
<p class="h4 text-center">
<strong>Interested in writing your own ES6 JavaScript plugins? Check out <a href="https://ES6.io/friend/JOHNSON">ES6.io</a> for great tutorials! 💪🏼</strong>
<p>
Choices.js is a lightweight, configurable select box/text input
plugin. Similar to Select2 and Selectize but without the jQuery
dependency.
</p>
<hr>
<p>
For all config options, visit the
<a href="https://github.com/jshjohnson/Choices">GitHub repo</a>.
</p>
<hr />
<p class="h4 text-center">
<strong
>Interested in writing your own ES6 JavaScript plugins? Check out
<a href="https://ES6.io/friend/JOHNSON">ES6.io</a> for great
tutorials! 💪🏼</strong
>
</p>
<hr />
<h2>Text inputs</h2>
<label for="choices-text-remove-button">Limited to 5 values with remove button</label>
<input class="form-control" id="choices-text-remove-button" type="text" value="preset-1,preset-2" placeholder="Enter something">
<label for="choices-text-remove-button"
>Limited to 5 values with remove button</label
>
<input
class="form-control"
id="choices-text-remove-button"
type="text"
value="preset-1,preset-2"
placeholder="Enter something"
/>
<label for="choices-text-unique-values">Unique values only, no pasting</label>
<input class="form-control" id="choices-text-unique-values" type="text" value="preset-1, preset-2" placeholder="This is a placeholder"
class="custom class">
<label for="choices-text-unique-values"
>Unique values only, no pasting</label
>
<input
class="form-control"
id="choices-text-unique-values"
type="text"
value="preset-1, preset-2"
placeholder="This is a placeholder"
class="custom class"
/>
<label for="choices-text-email-filter">Email addresses only</label>
<input class="form-control" id="choices-text-email-filter" type="text" placeholder="This is a placeholder">
<input
class="form-control"
id="choices-text-email-filter"
type="text"
placeholder="This is a placeholder"
/>
<label for="choices-text-disabled">Disabled</label>
<input class="form-control" id="choices-text-disabled" type="text" value="josh@joshuajohnson.co.uk, joe@bloggs.co.uk" placeholder="This is a placeholder">
<input
class="form-control"
id="choices-text-disabled"
type="text"
value="josh@joshuajohnson.co.uk, joe@bloggs.co.uk"
placeholder="This is a placeholder"
/>
<label for="choices-text-prepend-append-value">Prepends and appends a value to each items return value</label>
<input class="form-control" id="choices-text-prepend-append-value" type="text" value="preset-1, preset-2" placeholder="This is a placeholder">
<label for="choices-text-prepend-append-value"
>Prepends and appends a value to each items return value</label
>
<input
class="form-control"
id="choices-text-prepend-append-value"
type="text"
value="preset-1, preset-2"
placeholder="This is a placeholder"
/>
<label for="choices-text-preset-values">Preset values passed through options</label>
<input class="form-control" id="choices-text-preset-values" type="text" value="Michael Smith" placeholder="This is a placeholder">
<label for="choices-text-preset-values"
>Preset values passed through options</label
>
<input
class="form-control"
id="choices-text-preset-values"
type="text"
value="Michael Smith"
placeholder="This is a placeholder"
/>
<label for="choices-text-i18n">I18N labels</label>
<input class="form-control" id="choices-text-i18n" type="text">
<input class="form-control" id="choices-text-i18n" type="text" />
<label for="choices-text-rtl">Right-to-left</label>
<input data-trigger class="form-control" id="choices-text-rtl" type="text" value="Value 1, Value 2" dir="rtl">
<input
data-trigger
class="form-control"
id="choices-text-rtl"
type="text"
value="Value 1, Value 2"
dir="rtl"
/>
<hr>
<hr />
<h2>Multiple select input</h2>
<label for="choices-multiple-default">Default</label>
<select class="form-control" data-trigger name="choices-multiple-default" id="choices-multiple-default" placeholder="This is a placeholder"
multiple>
<select
class="form-control"
data-trigger
name="choices-multiple-default"
id="choices-multiple-default"
placeholder="This is a placeholder"
multiple
>
<option value="Choice 1" selected>Choice 1</option>
<option value="Choice 2">Choice 2</option>
<option value="Choice 3">Choice 3</option>
@ -92,8 +193,13 @@
</select>
<label for="choices-multiple-remove-button">With remove button</label>
<select class="form-control" name="choices-multiple-remove-button" id="choices-multiple-remove-button" placeholder="This is a placeholder"
multiple>
<select
class="form-control"
name="choices-multiple-remove-button"
id="choices-multiple-remove-button"
placeholder="This is a placeholder"
multiple
>
<option value="Choice 1" selected>Choice 1</option>
<option value="Choice 2">Choice 2</option>
<option value="Choice 3">Choice 3</option>
@ -101,8 +207,13 @@
</select>
<label for="choices-multiple-groups">Option groups</label>
<select class="form-control" name="choices-multiple-groups" id="choices-multiple-groups" placeholder="This is a placeholder"
multiple>
<select
class="form-control"
name="choices-multiple-groups"
id="choices-multiple-groups"
placeholder="This is a placeholder"
multiple
>
<optgroup label="UK">
<option value="London">London</option>
<option value="Manchester">Manchester</option>
@ -135,48 +246,98 @@
</optgroup>
</select>
<p><small>If the following example do not load, the Discogs rate limit has probably been reached. Try again later!</small></p>
<p>
<small
>If the following example do not load, the Discogs rate limit has
probably been reached. Try again later!</small
>
</p>
<label for="choices-multiple-remote-fetch">Options from remote source (Fetch API) &amp; limited to 5</label>
<select class="form-control" name="choices-multiple-remote-fetch" id="choices-multiple-remote-fetch" multiple></select>
<label for="choices-multiple-remote-fetch"
>Options from remote source (Fetch API) &amp; limited to 5</label
>
<select
class="form-control"
name="choices-multiple-remote-fetch"
id="choices-multiple-remote-fetch"
multiple
></select>
<label for="choices-multiple-rtl">Right-to-left</label>
<select class="form-control" data-trigger name="choices-multiple-rtl" id="choices-multiple-rtl" placeholder="This is a placeholder"
multiple dir="rtl">
<select
class="form-control"
data-trigger
name="choices-multiple-rtl"
id="choices-multiple-rtl"
placeholder="This is a placeholder"
multiple
dir="rtl"
>
<option value="Choice 1" selected>Choice 1</option>
<option value="Choice 2">Choice 2</option>
<option value="Choice 3">Choice 3</option>
<option value="Choice 4" disabled>Choice 4</option>
</select>
<label for="choices-multiple-labels">Use label in event (add/remove)</label>
<label for="choices-multiple-labels"
>Use label in event (add/remove)</label
>
<p id="message"></p>
<select id="choices-multiple-labels" multiple></select>
<hr>
<hr />
<h2>Single select input</h2>
<label for="choices-single-default">Default</label>
<select class="form-control" data-trigger name="choices-single-default" id="choices-single-default" placeholder="This is a search placeholder">
<select
class="form-control"
data-trigger
name="choices-single-default"
id="choices-single-default"
placeholder="This is a search placeholder"
>
<option value="">This is a placeholder</option>
<option value="Choice 1">Choice 1</option>
<option value="Choice 2">Choice 2</option>
<option value="Choice 3">Choice 3</option>
</select>
<p><small>If the following two examples do not load, the Discogs rate limit has probably been reached. Try again later!</small></p>
<p>
<small
>If the following two examples do not load, the Discogs rate limit
has probably been reached. Try again later!</small
>
</p>
<label for="choices-single-remote-fetch">Options from remote source (Fetch API)</label>
<select class="form-control" name="choices-single-remote-fetch" id="choices-single-remote-fetch">
<label for="choices-single-remote-fetch"
>Options from remote source (Fetch API)</label
>
<select
class="form-control"
name="choices-single-remote-fetch"
id="choices-single-remote-fetch"
>
<option value="">Pick an Arctic Monkeys' record</option>
</select>
<label for="choices-single-remove-xhr">Options from remote source (XHR) &amp; remove button</label>
<select class="form-control" name="choices-single-remove-xhr" id="choices-single-remove-xhr">
<label for="choices-single-remove-xhr"
>Options from remote source (XHR) &amp; remove button</label
>
<select
class="form-control"
name="choices-single-remove-xhr"
id="choices-single-remove-xhr"
>
<option value="">Pick a Smiths' record</option>
</select>
<label for="choices-single-groups">Option groups</label>
<select class="form-control" data-trigger name="choices-single-groups" id="choices-single-groups" placeholder="This is a placeholder">
<select
class="form-control"
data-trigger
name="choices-single-groups"
id="choices-single-groups"
placeholder="This is a placeholder"
>
<optgroup label="UK">
<option value="London">London</option>
<option value="Manchester">Manchester</option>
@ -210,35 +371,77 @@
</select>
<label for="choices-single-rtl">Right-to-left</label>
<select class="form-control" data-trigger name="choices-single-rtl" id="choices-single-rtl" placeholder="This is a placeholder"
dir="rtl">
<select
class="form-control"
data-trigger
name="choices-single-rtl"
id="choices-single-rtl"
placeholder="This is a placeholder"
dir="rtl"
>
<option value="Choice 1">Choice 1</option>
<option value="Choice 2">Choice 2</option>
<option value="Choice 3">Choice 3</option>
</select>
<label for="choices-single-no-search">Options added via config with no search</label>
<select class="form-control" name="choices-single-no-search" id="choices-single-no-search">
<label for="choices-single-no-search"
>Options added via config with no search</label
>
<select
class="form-control"
name="choices-single-no-search"
id="choices-single-no-search"
>
<option value="0">Zero</option>
</select>
<label for="choices-single-preset-options">Option and option groups added via config</label>
<select class="form-control" name="choices-single-preset-options" id="choices-single-preset-options" placeholder="This is a placeholder"></select>
<label for="choices-single-preset-options"
>Option and option groups added via config</label
>
<select
class="form-control"
name="choices-single-preset-options"
id="choices-single-preset-options"
placeholder="This is a placeholder"
></select>
<label for="choices-single-selected-option">Option selected via config with custom properties</label>
<p><small>Try searching for 'fantastic', "Label 3" should display</small></p>
<select class="form-control" name="choices-single-selected-option" id="choices-single-selected-option" placeholder="This is a placeholder"></select>
<label for="choices-single-selected-option"
>Option selected via config with custom properties</label
>
<p>
<small>Try searching for 'fantastic', "Label 3" should display</small>
</p>
<select
class="form-control"
name="choices-single-selected-option"
id="choices-single-selected-option"
placeholder="This is a placeholder"
></select>
<label for="choices-with-custom-props-via-html">Option searchable by custom properties via <code>data-custom-properties</code> attribute</label>
<p><small>Try searching for 'fantastic', "Label 3" should display</small></p>
<label for="choices-with-custom-props-via-html"
>Option searchable by custom properties via
<code>data-custom-properties</code> attribute</label
>
<p>
<small>Try searching for 'fantastic', "Label 3" should display</small>
</p>
<select class="form-control" id="choices-with-custom-props-via-html">
<option value="Dropdown item 1">Label One</option>
<option value="Dropdown item 2" selected disabled>Label Two</option>
<option value="Dropdown item 3" data-custom-properties='This option is fantastic'>Label Three</option>
<option
value="Dropdown item 3"
data-custom-properties="This option is fantastic"
>Label Three</option
>
</select>
<label for="choices-single-no-sorting">Options without sorting</label>
<select class="form-control" name="choices-single-no-sorting" id="choices-single-no-sorting" placeholder="This is a placeholder">
<select
class="form-control"
name="choices-single-no-sorting"
id="choices-single-no-sorting"
placeholder="This is a placeholder"
>
<option value="Madrid">Madrid</option>
<option value="Toronto">Toronto</option>
<option value="Vancouver">Vancouver</option>
@ -260,17 +463,30 @@
</select>
<label for="choices-single-custom-templates">Custom templates</label>
<select class="form-control" name="choices-single-custom-templates" id="choices-single-custom-templates" placeholder="This is a placeholder">
<select
class="form-control"
name="choices-single-custom-templates"
id="choices-single-custom-templates"
placeholder="This is a placeholder"
>
<option value="React">React</option>
<option value="Angular">Angular</option>
<option value="Ember">Ember</option>
<option value="Vue">Vue</option>
</select>
<p>Below is an example of how you could have two select inputs depend on eachother. 'Tube stations' will only be enabled if
the value of 'Cities' is 'London'</p>
<p>
Below is an example of how you could have two select inputs depend on
eachother. 'Tube stations' will only be enabled if the value of
'Cities' is 'London'
</p>
<label for="cities">Cities</label>
<select class="form-control" name="cities" id="cities" placeholder="Choose a city">
<select
class="form-control"
name="cities"
id="cities"
placeholder="Choose a city"
>
<option value="Leeds">Leeds</option>
<option value="Manchester">Manchester</option>
<option value="London">London</option>
@ -279,20 +495,32 @@
</select>
<label for="tube-stations">Tube stations</label>
<select class="form-control" name="tube-stations" id="tube-stations" placeholder="Choose a tube station">
<select
class="form-control"
name="tube-stations"
id="tube-stations"
placeholder="Choose a tube station"
>
<option value="Moorgate">Moorgate</option>
<option value="St Pauls">St Pauls</option>
<option value="Old Street">Old Street</option>
<option value="Liverpool Street">Liverpool Street</option>
<option value="Kings Cross St. Pancras">Kings Cross St. Pancras</option>
<option value="Kings Cross St. Pancras"
>Kings Cross St. Pancras</option
>
</select>
<hr>
<hr />
<h2>Form interaction</h2>
<p>Change the values and press reset to restore to initial state.</p>
<form>
<label for="reset-simple">Change me!</label>
<select class="form-control" name="reset-simple" id="reset-simple" placeholder="Choose an option">
<select
class="form-control"
name="reset-simple"
id="reset-simple"
placeholder="Choose an option"
>
<option value="Option 1">Option 1</option>
<option value="Option 2" selected>Option 2</option>
<option value="Option 3">Option 3</option>
@ -301,8 +529,13 @@
</select>
<label for="reset-multiple">And me!</label>
<select class="form-control" name="reset-multiple" id="reset-multiple" placeholder="This is a placeholder"
multiple>
<select
class="form-control"
name="reset-multiple"
id="reset-multiple"
placeholder="This is a placeholder"
multiple
>
<option value="Choice 1" selected>Choice 1</option>
<option value="Choice 2">Choice 2</option>
<option value="Choice 3">Choice 3</option>
@ -315,12 +548,15 @@
</div>
<script>
document.addEventListener('DOMContentLoaded', function() {
var textRemove = new Choices(document.getElementById('choices-text-remove-button'), {
var textRemove = new Choices(
document.getElementById('choices-text-remove-button'),
{
delimiter: ',',
editItems: true,
maxItemCount: 5,
removeItemButton: true,
});
},
);
var textUniqueVals = new Choices('#choices-text-unique-values', {
paste: false,
@ -334,7 +570,9 @@
editItems: true,
maxItemCount: 5,
addItemText: function(value) {
return 'Appuyez sur Entrée pour ajouter <b>"' + String(value) + '"</b>';
return (
'Appuyez sur Entrée pour ajouter <b>"' + String(value) + '"</b>'
);
},
maxItemText: function(maxItemCount) {
return String(maxItemCount) + 'valeurs peuvent être ajoutées';
@ -344,12 +582,12 @@
var textEmailFilter = new Choices('#choices-text-email-filter', {
editItems: true,
addItemFilterFn: function (value) {
addItemFilter: function(value) {
if (!value) {
return false;
}
const regex = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
const regex = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
const expression = new RegExp(regex.source, 'i');
return expression.test(value);
},
@ -360,29 +598,39 @@
removeItems: false,
}).disable();
var textPrependAppendVal = new Choices('#choices-text-prepend-append-value', {
var textPrependAppendVal = new Choices(
'#choices-text-prepend-append-value',
{
prependValue: 'item-',
appendValue: '-' + Date.now(),
}).removeActiveItems();
},
).removeActiveItems();
var textPresetVal = new Choices('#choices-text-preset-values', {
items: ['Josh Johnson', {
items: [
'Josh Johnson',
{
value: 'joe@bloggs.co.uk',
label: 'Joe Bloggs',
customProperties: {
description: 'Joe Blogg is such a generic name'
}
}],
description: 'Joe Blogg is such a generic name',
},
},
],
});
var multipleDefault = new Choices(document.getElementById('choices-multiple-groups'));
var multipleDefault = new Choices(
document.getElementById('choices-multiple-groups'),
);
var multipleFetch = new Choices('#choices-multiple-remote-fetch', {
placeholder: true,
placeholderValue: 'Pick an Strokes record',
maxItemCount: 5,
}).ajax(function(callback) {
fetch('https://api.discogs.com/artists/55980/releases?token=QBRmstCkwXEvCjTclCpumbtNwvVkEzGAdELXyRyW')
fetch(
'https://api.discogs.com/artists/55980/releases?token=QBRmstCkwXEvCjTclCpumbtNwvVkEzGAdELXyRyW',
)
.then(function(response) {
response.json().then(function(data) {
callback(data.releases, 'title', 'title');
@ -393,9 +641,12 @@
});
});
var multipleCancelButton = new Choices('#choices-multiple-remove-button', {
var multipleCancelButton = new Choices(
'#choices-multiple-remove-button',
{
removeItemButton: true,
});
},
);
/* Use label on event */
var choicesSelect = new Choices('#choices-multiple-labels', {
@ -405,24 +656,39 @@
{ value: 'Two', label: 'Label Two', disabled: true },
{ value: 'Three', label: 'Label Three' },
],
}).setChoices([
}).setChoices(
[
{ value: 'Four', label: 'Label Four', disabled: true },
{ value: 'Five', label: 'Label Five' },
{ value: 'Six', label: 'Label Six', selected: true },
], 'value', 'label', false);
],
'value',
'label',
false,
);
choicesSelect.passedElement.element.addEventListener('addItem', function(event) {
document.getElementById('message').innerHTML = 'You just added "' + event.detail.label + '"';
});
choicesSelect.passedElement.element.addEventListener(
'addItem',
function(event) {
document.getElementById('message').innerHTML =
'You just added "' + event.detail.label + '"';
},
);
choicesSelect.passedElement.element.addEventListener('removeItem', function(event) {
document.getElementById('message').innerHTML = 'You just removed "' + event.detail.label + '"';
});
choicesSelect.passedElement.element.addEventListener(
'removeItem',
function(event) {
document.getElementById('message').innerHTML =
'You just removed "' + event.detail.label + '"';
},
);
var singleFetch = new Choices('#choices-single-remote-fetch', {
searchPlaceholderValue: 'Search for an Arctic Monkeys record',
}).ajax(function(callback) {
fetch('https://api.discogs.com/artists/391170/releases?token=QBRmstCkwXEvCjTclCpumbtNwvVkEzGAdELXyRyW')
fetch(
'https://api.discogs.com/artists/391170/releases?token=QBRmstCkwXEvCjTclCpumbtNwvVkEzGAdELXyRyW',
)
.then(function(response) {
response.json().then(function(data) {
callback(data.releases, 'title', 'title');
@ -436,10 +702,14 @@
var singleXhrRemove = new Choices('#choices-single-remove-xhr', {
removeItemButton: true,
searchPlaceholderValue: 'Search for a Smiths\' record'
searchPlaceholderValue: "Search for a Smiths' record",
}).ajax(function(callback) {
var request = new XMLHttpRequest();
request.open('get', 'https://api.discogs.com/artists/83080/releases?token=QBRmstCkwXEvCjTclCpumbtNwvVkEzGAdELXyRyW', true);
request.open(
'get',
'https://api.discogs.com/artists/83080/releases?token=QBRmstCkwXEvCjTclCpumbtNwvVkEzGAdELXyRyW',
true,
);
request.onreadystatechange = function() {
var status;
var data;
@ -453,13 +723,13 @@
console.error(status);
}
}
}
};
request.send();
});
var genericExamples = new Choices('[data-trigger]', {
placeholderValue: 'This is a placeholder set in the config',
searchPlaceholderValue: 'This is a search placeholder'
searchPlaceholderValue: 'This is a search placeholder',
});
var singleNoSearch = new Choices('#choices-single-no-search', {
@ -470,15 +740,22 @@
{ value: 'Two', label: 'Label Two', disabled: true },
{ value: 'Three', label: 'Label Three' },
],
}).setChoices([
}).setChoices(
[
{ value: 'Four', label: 'Label Four', disabled: true },
{ value: 'Five', label: 'Label Five' },
{ value: 'Six', label: 'Label Six', selected: true },
], 'value', 'label', false);
],
'value',
'label',
false,
);
var singlePresetOpts = new Choices('#choices-single-preset-options', {
placeholder: true,
}).setChoices([{
}).setChoices(
[
{
label: 'Group one',
id: 1,
disabled: false,
@ -486,7 +763,7 @@
{ value: 'Child One', label: 'Child One', selected: true },
{ value: 'Child Two', label: 'Child Two', disabled: true },
{ value: 'Child Three', label: 'Child Three' },
]
],
},
{
label: 'Group two',
@ -496,8 +773,12 @@
{ value: 'Child Four', label: 'Child Four', disabled: true },
{ value: 'Child Five', label: 'Child Five' },
{ value: 'Child Six', label: 'Child Six' },
]
}], 'value', 'label');
],
},
],
'value',
'label',
);
var singleSelectedOpt = new Choices('#choices-single-selected-option', {
searchFields: ['label', 'value', 'customProperties.description'],
@ -505,23 +786,30 @@
{ value: 'One', label: 'Label One', selected: true },
{ value: 'Two', label: 'Label Two', disabled: true },
{
value: 'Three', label: 'Label Three', customProperties: {
description: 'This option is fantastic'
}
value: 'Three',
label: 'Label Three',
customProperties: {
description: 'This option is fantastic',
},
},
],
}).setChoiceByValue('Two');
var customChoicesPropertiesViaDataAttributes = new Choices('#choices-with-custom-props-via-html', {
searchFields: ['label', 'value', 'customProperties']
})
var customChoicesPropertiesViaDataAttributes = new Choices(
'#choices-with-custom-props-via-html',
{
searchFields: ['label', 'value', 'customProperties'],
},
);
var singleNoSorting = new Choices('#choices-single-no-sorting', {
shouldSort: false,
});
var cities = new Choices(document.getElementById('cities'));
var tubeStations = new Choices(document.getElementById('tube-stations')).disable();
var tubeStations = new Choices(
document.getElementById('tube-stations'),
).disable();
cities.passedElement.element.addEventListener('change', function(e) {
if (e.detail.value === 'London') {
@ -531,43 +819,96 @@
}
});
var customTemplates = new Choices(document.getElementById('choices-single-custom-templates'), {
var customTemplates = new Choices(
document.getElementById('choices-single-custom-templates'),
{
callbackOnCreateTemplates: function(strToEl) {
var classNames = this.config.classNames;
var itemSelectText = this.config.itemSelectText;
return {
item: function(classNames, data) {
return strToEl('\
return strToEl(
'\
<div\
class="'+ String(classNames.item) + ' ' + String(data.highlighted ? classNames.highlightedState : classNames.itemSelectable) + '"\
class="' +
String(classNames.item) +
' ' +
String(
data.highlighted
? classNames.highlightedState
: classNames.itemSelectable,
) +
'"\
data-item\
data-id="'+ String(data.id) + '"\
data-value="'+ String(data.value) + '"\
'+ String(data.active ? 'aria-selected="true"' : '') + '\
'+ String(data.disabled ? 'aria-disabled="true"' : '') + '\
data-id="' +
String(data.id) +
'"\
data-value="' +
String(data.value) +
'"\
' +
String(data.active ? 'aria-selected="true"' : '') +
'\
' +
String(data.disabled ? 'aria-disabled="true"' : '') +
'\
>\
<span style="margin-right:10px;">🎉</span> ' + String(data.label) + '\
<span style="margin-right:10px;">🎉</span> ' +
String(data.label) +
'\
</div>\
');
',
);
},
choice: function(classNames, data) {
return strToEl('\
return strToEl(
'\
<div\
class="'+ String(classNames.item) + ' ' + String(classNames.itemChoice) + ' ' + String(data.disabled ? classNames.itemDisabled : classNames.itemSelectable) + '"\
data-select-text="'+ String(itemSelectText) + '"\
class="' +
String(classNames.item) +
' ' +
String(classNames.itemChoice) +
' ' +
String(
data.disabled
? classNames.itemDisabled
: classNames.itemSelectable,
) +
'"\
data-select-text="' +
String(itemSelectText) +
'"\
data-choice \
'+ String(data.disabled ? 'data-choice-disabled aria-disabled="true"' : 'data-choice-selectable') + '\
data-id="'+ String(data.id) + '"\
data-value="'+ String(data.value) + '"\
'+ String(data.groupId > 0 ? 'role="treeitem"' : 'role="option"') + '\
' +
String(
data.disabled
? 'data-choice-disabled aria-disabled="true"'
: 'data-choice-selectable',
) +
'\
data-id="' +
String(data.id) +
'"\
data-value="' +
String(data.value) +
'"\
' +
String(
data.groupId > 0 ? 'role="treeitem"' : 'role="option"',
) +
'\
>\
<span style="margin-right:10px;">👉🏽</span> ' + String(data.label) + '\
<span style="margin-right:10px;">👉🏽</span> ' +
String(data.label) +
'\
</div>\
');
',
);
},
};
}
});
},
},
);
var resetSimple = new Choices(document.getElementById('reset-simple'));
@ -579,12 +920,16 @@
<!-- Google Analytics - Ignore me -->
<script>
window.ga = window.ga || function() { (ga.q = ga.q || []).push(arguments) }; ga.l = +new Date;
window.ga =
window.ga ||
function() {
(ga.q = ga.q || []).push(arguments);
};
ga.l = +new Date();
ga('create', 'UA-31575166-1', 'auto');
ga('send', 'pageview');
</script>
<script async src='https://www.google-analytics.com/analytics.js'></script>
<script async src="https://www.google-analytics.com/analytics.js"></script>
<!-- End Google Analytics -->
</body>
</body>
</html>

View file

@ -1,26 +1,56 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width,initial-scale=1,user-scalable=no">
<head>
<meta charset="UTF-8" />
<meta
name="viewport"
content="width=device-width,initial-scale=1,user-scalable=no"
/>
<title>Choices</title>
<meta name=description itemprop=description content="A lightweight, configurable select box/text input plugin. Similar to Select2 and Selectize but without the jQuery dependency.">
<link rel="apple-touch-icon" sizes="180x180" href="../assets/images/apple-touch-icon.png">
<link rel="icon" type="image/png" href="../assets/images/favicon-32x32.png" sizes="32x32">
<link rel="icon" type="image/png" href="../assets/images/favicon-16x16.png" sizes="16x16">
<link rel="manifest" href="../assets/images/manifest.json">
<link rel="mask-icon" href="../assets/images/safari-pinned-tab.svg" color="#00bcd4">
<link rel="shortcut icon" href="../assets/images/favicon.ico">
<meta name="msapplication-config" content="../assets/images/browserconfig.xml">
<meta name="theme-color" content="#ffffff">
<meta
name="description"
itemprop="description"
content="A lightweight, configurable select box/text input plugin. Similar to Select2 and Selectize but without the jQuery dependency."
/>
<link
rel="apple-touch-icon"
sizes="180x180"
href="../assets/images/apple-touch-icon.png"
/>
<link
rel="icon"
type="image/png"
href="../assets/images/favicon-32x32.png"
sizes="32x32"
/>
<link
rel="icon"
type="image/png"
href="../assets/images/favicon-16x16.png"
sizes="16x16"
/>
<link rel="manifest" href="../assets/images/manifest.json" />
<link
rel="mask-icon"
href="../assets/images/safari-pinned-tab.svg"
color="#00bcd4"
/>
<link rel="shortcut icon" href="../assets/images/favicon.ico" />
<meta
name="msapplication-config"
content="../assets/images/browserconfig.xml"
/>
<meta name="theme-color" content="#ffffff" />
<!-- Ignore these -->
<link rel="stylesheet" href="../assets/styles/base.min.css?version=6.0.3">
<link rel="stylesheet" href="../assets/styles/base.min.css?version=6.0.3" />
<!-- End ignore these -->
<!-- Choices includes -->
<link rel="stylesheet" href="../assets/styles/choices.min.css?version=6.0.3">
<link
rel="stylesheet"
href="../assets/styles/choices.min.css?version=6.0.3"
/>
<script src="../assets/scripts/choices.min.js?version=6.0.3"></script>
<!-- End Choices includes -->
</head>
@ -31,63 +61,76 @@
<h2>Text inputs</h2>
<div data-test-hook="basic">
<label for="choices-basic">Basic</label>
<input class="form-control" id="choices-basic" type="text">
<input class="form-control" id="choices-basic" type="text" />
</div>
<div data-test-hook="edit-items">
<label for="choices-edit-items">Edit items</label>
<input class="form-control" id="choices-edit-items" type="text">
<input class="form-control" id="choices-edit-items" type="text" />
</div>
<div data-test-hook="remove-button">
<label for="choices-remove-button">Remove button</label>
<input class="form-control" id="choices-remove-button" type="text">
<input class="form-control" id="choices-remove-button" type="text" />
</div>
<div data-test-hook="unique-values">
<label for="choices-unique-values">Unique values</label>
<input class="form-control" id="choices-unique-values" type="text">
<input class="form-control" id="choices-unique-values" type="text" />
</div>
<div data-test-hook="input-limit">
<label for="choices-input-limit">Input limit</label>
<input class="form-control" id="choices-input-limit" type="text">
<input class="form-control" id="choices-input-limit" type="text" />
</div>
<div data-test-hook="add-item-filter">
<label for="choices-add-item-filter">Add item filter</label>
<input class="form-control" id="choices-add-item-filter" type="text">
<input
class="form-control"
id="choices-add-item-filter"
type="text"
/>
</div>
<div data-test-hook="adding-items-disabled">
<label for="choices-adding-items-disabled">Add items disabled</label>
<input class="form-control" id="choices-adding-items-disabled" type="text">
<input
class="form-control"
id="choices-adding-items-disabled"
type="text"
/>
</div>
<div data-test-hook="disabled-via-attr">
<label for="choices-disabled-via-attr">Disabled via attribute</label>
<input class="form-control" id="choices-disabled-via-attr" type="text" disabled>
<input
class="form-control"
id="choices-disabled-via-attr"
type="text"
disabled
/>
</div>
<div data-test-hook="prepend-append">
<label for="choices-prepend-append">Prepend/append</label>
<input class="form-control" id="choices-prepend-append" type="text">
<input class="form-control" id="choices-prepend-append" type="text" />
</div>
<div data-test-hook="prepopulated">
<label for="choices-prepopulated">Pre-populated choices</label>
<input class="form-control" id="choices-prepopulated" type="text">
<input class="form-control" id="choices-prepopulated" type="text" />
</div>
<div data-test-hook="placeholder">
<label for="choices-placeholder">Placeholder</label>
<input class="form-control" id="choices-placeholder" type="text">
<input class="form-control" id="choices-placeholder" type="text" />
</div>
<div data-test-hook="within-form">
<form>
<label for="choices-within-form">Within form</label>
<input class="form-control" id="choices-within-form" type="text">
<input class="form-control" id="choices-within-form" type="text" />
</form>
</div>
</div>
@ -114,8 +157,8 @@
new Choices('#choices-add-item-filter', {
addItems: true,
addItemFilterFn: (value) => {
const regex = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/
addItemFilter: value => {
const regex = /^(([^<>()\[\]\\.,;:\s@"]+(\.[^<>()\[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/;
const expression = new RegExp(regex.source, 'i');
return expression.test(value);
},
@ -133,13 +176,16 @@
});
new Choices('#choices-prepopulated', {
items: ['Josh Johnson', {
items: [
'Josh Johnson',
{
value: 'joe@bloggs.co.uk',
label: 'Joe Bloggs',
customProperties: {
description: 'Joe Blogg is such a generic name',
}
}],
},
},
],
});
new Choices('#choices-placeholder', {
@ -151,4 +197,4 @@
});
</script>
</body>
</html>
</html>

View file

@ -79,6 +79,18 @@ class Choices {
{ arrayMerge: (destinationArray, sourceArray) => [...sourceArray] },
);
// Convert addItemFilter to function
if (
userConfig.addItemFilter &&
typeof userConfig.addItemFilter !== 'function'
) {
const re =
userConfig.addItemFilter instanceof RegExp
? userConfig.addItemFilter
: new RegExp(userConfig.addItemFilter);
this.config.addItemFilter = re.test.bind(re);
}
const invalidConfigOptions = diff(this.config, DEFAULT_CONFIG);
if (invalidConfigOptions.length) {
console.warn(
@ -1026,11 +1038,12 @@ class Choices {
this._isTextElement &&
this.config.addItems &&
canAddItem &&
isType('Function', this.config.addItemFilterFn) &&
!this.config.addItemFilterFn(value)
typeof this.config.addItemFilter === 'function' &&
!this.config.addItemFilter(value)
) {
canAddItem = false;
notice = isType('Function', this.config.customAddItemText)
notice =
typeof this.config.customAddItemText === 'function'
? this.config.customAddItemText(value)
: this.config.customAddItemText;
}

View file

@ -35,7 +35,7 @@ export const DEFAULT_CONFIG = {
renderChoiceLimit: -1,
maxItemCount: -1,
addItems: true,
addItemFilterFn: null,
addItemFilter: null,
removeItems: true,
removeItemButton: false,
editItems: false,

View file

@ -55,7 +55,7 @@ describe('constants', () => {
expect(DEFAULT_CONFIG.renderChoiceLimit).to.be.a('number');
expect(DEFAULT_CONFIG.maxItemCount).to.be.a('number');
expect(DEFAULT_CONFIG.addItems).to.be.a('boolean');
expect(DEFAULT_CONFIG.addItemFilterFn).to.equal(null);
expect(DEFAULT_CONFIG.addItemFilter).to.equal(null);
expect(DEFAULT_CONFIG.removeItems).to.be.a('boolean');
expect(DEFAULT_CONFIG.removeItemButton).to.be.a('boolean');
expect(DEFAULT_CONFIG.editItems).to.be.a('boolean');

3
types/index.d.ts vendored
View file

@ -18,6 +18,7 @@ declare namespace Choices {
type stringFunction = () => string;
type noticeStringFunction = (value: string) => string;
type noticeLimitFunction = (maxItemCount: number) => string;
type filterFunction = (value: string) => boolean;
}
interface Choice {
@ -403,7 +404,7 @@ declare namespace Choices {
*
* @default null
*/
addItemFilterFn: (value: string) => boolean;
addItemFilter: string | RegExp | Choices.Types.filterFunction;
/**
* The text that is shown when a user has inputted a new item but has not pressed the enter key. To access the current input value, pass a function with a `value` argument (see the **default config** [https://github.com/jshjohnson/Choices#setup] for an example), otherwise pass a string.