Reputation: 771
I have the following HTML/Bootstrap element:
<div class="form-group">
<label>Keyword:</label>
<input type="text" class="form-control" id="keyword">
</div>
I want to allow the user to select predefined words as he is typing text into this form using selectize.js. If no word is selected, then input value is the word user typed in.
How can i do this using selectize.js?
EDIT:
The thing is: i need to populate these keyword fields with predefined values extracted from document (i'm actually making an editor), and if i use "select" elements instead of "input", I can't set starting values with:
$('#keyword').val();
Since these starting values can be random, I cant figure a way to work around this.
Upvotes: 1
Views: 4983
Reputation: 771
I figured out how to do this:
//enable selectize on input element and add a list of options
var $select = $('#keyword').selectize({
maxItems: 1,
valueField: 'id',
labelField: 'title',
searchField: 'title',
options: [
{id: 1, title: 'value1'},
{id: 2, title: 'value2'},
{id: 3, title: 'value3'}
],
create: true,
});
//store selectize object to variable
var selectize = $select[0].selectize;
//add new option and set the value to new option
selectize.addOption({id:4, title: 'value4'});
selectize.setValue(4, false);
Now the default option after loading the page is 'value4' and other options can be selected as required.
Upvotes: 0
Reputation: 15616
You can use create
or createOnBlur
options on initialization;
Here's the documentation of selectize.js
https://github.com/selectize/selectize.js/blob/master/docs/usage.md
create
Allows the user to create new items that aren't in the initial list of options.
createOnBlur
If true, when user exits the field (clicks outside of input), a new option is created and selected (if create setting is enabled)
Upvotes: 3