Reputation: 123490
My original select box has the required
attribute set
<select name="some-name" value="initialValue" required>
<option value="initialValue">initial value</option>
<option value="otherValue">other value</option>
</select>
I start selectize:
$("select[name='some-name']").selectize()
But users can still use the backspace key to remove the selected option, making the select box have a value of ''
.
Since required
on the real select box doesn't seem to affect Selectize, I've read the selectize documentation but can't find any way to stop users from deleting the option.
How can I prevent users from setting the value to anything except a valid option?
Upvotes: 4
Views: 5442
Reputation: 98
You could check to see if the selected options are less than 1 when removing an option, if it is add the item back. getValue() returns an array of currently selected values.
To the user it just looks like its undeletable or not removable.
var userSelectize = $(...).selectize({});
userSelectize[0].selectize.on("item_remove", function(value, item) {
if (userSelectize[0].selectize.getValue().length < 1) {
this.addItem(value);
}
});
Upvotes: 2
Reputation: 123490
Using Selectize no-delete works fine. Since I use npm:
var Selectize = require('selectize');
// https://github.com/akrikos/selectize-no-delete/blob/master/src/selectize-no-delete.js
Selectize.define('no-delete', function(options) {
this.deleteSelection = function() {};
});
Then, when you make a selectize instance:
$("select[name='country-code']").selectize({
plugins: {
'no-delete': {}
},
....
})
Upvotes: 0