HTML Element Wrapper and Dynamically Filled Options Functionality for Choices.js
Note: Choices.js must be installed. See Choices.js for installation directions.
Download code from GitHub or install using NPM:
npm install https://github.com/anthonywoodard/dynamic-choices
const dc = DynamicChoices({
defaultConfig: {
placeholderValue: "Start typing here",
},
paramConfig: {
apiUrl: "/api",
searchButtonClassNames: "btn btn-outline-primary",
searchButtonInnerHtml: "<i class="fa fa-search" aria-hidden="true"></i>",
boxClassNames: "d-flex justify-content-between mb-4",
xhrQueryKey: "query",
searchButtonClickCallback: function(){
console.log('searched')
}
}
})
Add the dynamic-choices element to the template
<form>
<dynamic-choices/>
</form>
Choices.js options can be passed in via the defaultConfig
object parameter. All options can be configured except:
- noChoicesText
- shouldSort
- searchChoices
- removeItemButton
- duplicateItemsAllowed
- placeholderValue: 'Start typing'
- itemSelectText: 'Press enter to select'
{
boxId: '',
boxClassNames: '',
searchButtonId: '',
searchButtonTitle: 'Search',
searchButtonClassNames: '',
searchButtonInnerHtml: 'Search',
clearButtonId: '',
clearButtonTitle: 'Clear',
clearButtonClassNames: '',
clearButtonInnerHtml: 'Clear',
transformValueFnc: false, // function
apiUrl: '',
searchValue: 'id',
labelValue: 'text',
xhrMethod: 'POST',
xhrProgressCallback: false, // function
xhrErrorCallback: false, // function
xhrResponseErrorCallback: false, // function
xhrHeaders: [
{
'Content-type': 'application/x-www-form-urlencoded'
}
],
xhrResponseType: 'json',
xhrQueryKey: '',
lookupDelay: 300,
searchButtonClickCallback: false, // function
addChoiceCallback: false, // function
removeItemCallback: false // function
}
Usage: paramObj is an object and must have value
key. If paramObj has removeAll: true
then all active items will be removed first.
Usage: Removes all items.
Usage: Removes item by value.
Usage: Get value(s) of input (i.e. inputted items (text) or selected choices (select)). Optionally pass an argument of true to only return values rather than value objects.