Reputation: 233
I am trying to set the option to be selected in the selectize.js, how to do that.
There are options that can be set initially. How can i set the value then.
<select id="selectize">
</select>
var options=[
{value:0, text:"option 0"},
{value:1, text:"option 1"},
{value:2, text:"option 2"},
{value:3, text:"option 3"},
];
$('#selectize').selectize({
"options":options
});
$('#selectize').change(function(){
//$('#result').html("you select value="+$(this).val());
$('#selectize').val(1);
});
Please find the code in jsfiddle
Thanks,
Upvotes: 5
Views: 16768
Reputation: 658
Okay, left a comment about what a beating it is with the other solutions. Looks like selectize prefers working with the regular DOM vs. jQuery, which is actually a good thing, given recent move towards Vanilla JS.
So, here is a better solution. Just bear in mind there's no checking for the the element not being found. I'm sure you can decipher that. (And to the critics, there's nothing in the OP about jQuery.)
document.getElementById("editGenre").selectize.setValue("Rock");
Upvotes: 0
Reputation: 99
To set a selected option you need to use setValue if the selectize is a dropdown and you want to use it as a select dropdown. Suppose that you already have the preselected value and the selectize componente is already built and load all the values.
if you want dynamically change the value
var idPreselected = 2;
var $select = $('#MySelectizeDropdown').selectize();
var control = $select[0].selectize;
control.setValue(idPreselected);
Upvotes: 2
Reputation: 81
You can achieve this in four easy steps:
var val= "abc";
$("#txtbox").selectize()[0].selectize.destroy();
$('#txtbox').val(val);
$('#txtbox').selectize({
plugins: ['remove_button', 'restore_on_backspace'],
persist: false,
// createOnBlur: true,
create: true,
onItemAdd: function () {
this.close();
}
});
Upvotes: -1
Reputation: 74
To set an initial value for your selectize control use the addItem method.
var selectField = $('#yourfield');
if (selectField.length > 0) {
var selectField = $('#yourfield')[0].selectize;
selectField.addItem(IDTOSET, false);
}
https://jsfiddle.net/3aapx1m1/
Upvotes: 0
Reputation: 499
You have to select your selectize first with input[0].selectize
and then use the native method getValue()
of selectize.
Based on your fiddle this should work :
var options=[
{value:0, text:"option 0"},
{value:1, text:"option 1"},
{value:2, text:"option 2"},
{value:3, text:"option 3"},
];
$('#selectize').selectize({
"options":options
});
$('#selectize').change(function(){
var selectize = $("#selectize")[0].selectize;
$('#result').html("you select value="+ selectize.getValue());
});
Upvotes: 1