Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I make a selectize.js select box require a value?

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?

like image 460
mikemaccana Avatar asked Sep 11 '25 06:09

mikemaccana


1 Answers

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);
            }
    });
like image 55
WadeTheFade Avatar answered Sep 13 '25 18:09

WadeTheFade