How to set a value for a selectize.js input?
Asked Answered
L

12

74

I have a form from which I would like to copy some default values into the inputs. The form inputs are using the selectize.js plugin. I would like to set some of the form values programatically. The standard way of doing this:

$("#my_input").val("My Default Value");

does not work.

I have tried something like this but it does not work either.

var $select = $("#my_input").selectize();
var selectize = $select[0].selectize;
selectize.setValue("My Default Value"); 

Any ideas? It's got to be easy :) I'm missing it.

Ledeen answered 22/2, 2014 at 23:35 Comment(0)
S
89

Check the API Docs

Methods addOption(data) and setValue(value) might be what you are looking for.


Update: Seeing the popularity of this answer, here is some additional info based on comments/requests...

setValue(value, silent)
  Resets the selected items to the given value.
  If "silent" is truthy (ie: true, 1), no change event will be fired on the original input.

addOption(data)
  Adds an available option, or array of options. If it already exists, nothing will happen.
  Note: this does not refresh the options list dropdown (use refreshOptions() for that).


In response to options being overwritten:
This can happen by re-initializing the select without using the options you initially provided. If you are not intending to recreate the element, simply store the selectize object to a variable:

// 1. Only set the below variables once (ideally)
var $select = $('select').selectize(options);  // This initializes the selectize control
var selectize = $select[0].selectize; // This stores the selectize object to a variable (with name 'selectize')

// 2. Access the selectize object with methods later, for ex:
selectize.addOption(data);
selectize.setValue('something', false);


// Side note:
// You can set a variable to the previous options with
var old_options = selectize.settings;
// If you intend on calling $('select').selectize(old_options) or something
Shaylashaylah answered 22/2, 2014 at 23:49 Comment(7)
I did read the docs and have tried your suggestion. See my example. See does not work. I'm sure going to kick myself when I find the answer.Ledeen
You don't have quotes around #my_input in your jQuery selector.Shaylashaylah
Thanks for catching the typo. I had it correct in my original code and missed it when I copied to stackoverflow. The good news is that the works as I stated. I had a typo in my actual form that was the cause of the problem.Ledeen
Your answer put me on the right track. Beware though of one point: it seems that setValue will silently dismiss options not in the list, at least in my tests. See github.com/brianreavis/selectize.js/issues/568 for report and jsfiddle.Bylaw
how do you do this with the Angular version?Clypeate
When you call $("#my_input").selectize(), your original settings (i.e. plugins, render function, etc) are getting overwritten. How do you get the selectize object to call setValue() without overriding those settings?Dietrich
there isnt a way to have it set to the selected value from the options list?Merrile
D
42

This works for me:

var $select = $("#my_input").selectize();
var selectize = $select[0].selectize;
selectize.setValue(selectize.search("My Default Value").items[0].id);

but you have to be really really sure that you only have one match.

Update: As this solution works perfect, in-order to make it working even if there are multiple select elements on page I have updated the answer:

Following way we can initialize:

$('select').each(function (idx) {
    var selectizeInput = $(this).selectize(options);
    $(this).data('selectize', selectizeInput[0].selectize);
});

Setting value pragmatically post initialization:

var selectElement = $('#unique_selector').eq(0);
var selectize = selectElement.data('selectize');
if (!!selectize) selectize.setValue("My Default Value");
Donnell answered 5/10, 2015 at 21:21 Comment(1)
thanks for your answer, but for me its worked without search like this selectize.setValue("My Default Value"); you right on this case too, we have to make sure value is not repeat.Nara
C
19

A simplified answer:

$('#my_input').data('selectize').setValue("Option Value Here");
Caines answered 19/12, 2018 at 6:58 Comment(0)
S
15

Answer by the user 'onlyblank' is correct. A small addition to that- You can set more than 1 default values if you want.

Instead of passing on id to the setValue(), pass an array. Example:

var $select = $("#my_input").selectize();
var selectize = $select[0].selectize;
var defaultValueIds = [1,2]; # find the ids using search as shown by the user onlyblank
selectize.setValue(defaultValueIds);
Salish answered 27/5, 2016 at 13:29 Comment(0)
W
15

Here is my full code using tag from remote search. Hope this is helpful.

$('#myInput').selectize({
valueField: 'id',
labelField: 'name',
searchField: 'name',
options: [],
delimiter: ',',
persist: false,
create: false,
load: function(query, callback) {
    if (!query.length) return callback();
    $.ajax({
        url: '/api/all_cities.php',
        type: 'GET',
        dataType: 'json',
        data: {
            name: query,
        },
        error: function() {
            callback();
        },
        success: function(res) {
            callback(res);
        }
    });
},
onInitialize: function(){
    var selectize = this;
    $.get("/api/selected_cities.php", function( data ) {
        selectize.addOption(data); // This is will add to option
        var selected_items = [];
        $.each(data, function( i, obj) {
            selected_items.push(obj.id);
        });
        selectize.setValue(selected_items); //this will set option values as default
    });
}
});
Wive answered 13/2, 2017 at 16:10 Comment(0)
R
6

Note setValue only works if there are already predefined set of values for the selectize control ( ex. select field ), for controls where the value could be dynamic ( ex. user can add values on the fly, textbox field ) setValue ain't gonna work.

Use createItem functon instead for adding and setting the current value of the selectize field

ex.

$selectize[ 0 ].selectize.clear(); // Clear existing entries
for ( var i = 0 ; i < data_source.length ; i++ ) // data_source is a dynamic source of data
    $selectize[ 0 ].selectize.createItem( data_source[ i ] , false ); // false means don't trigger dropdown
Roselba answered 19/10, 2016 at 3:29 Comment(0)
R
6

just ran into the same problem and solved it with the following line of code:

selectize.addOption({text: "My Default Value", value: "My Default Value"});
selectize.setValue("My Default Value"); 
Respectable answered 27/1, 2017 at 8:12 Comment(1)
how to do in multiselect?Maurilla
S
2

I was having this same issue - I am using Selectize with Rails and wanted to Selectize an association field - I wanted the name of the associated record to show up in the dropdown, but I needed the value of each option to be the id of the record, since Rails uses the value to set associations.

I solved this by setting a coffeescript var of @valueAttr to the id of each object and a var of @dataAttr to the name of the record. Then I went through each option and set:

 opts.labelField = @dataAttr
 opts.valueField = @valueAttr

It helps to see the full diff: https://github.com/18F/C2/pull/912/files

Swanhilda answered 2/2, 2016 at 19:17 Comment(0)
I
1

I had a similar problem. My data is provided by a remote server. I want some value to be entered in the selectize box, but it is not sure in advance whether this value is a valid one on the server.

So I want the value to be entered in the box, and I want selectize to show the possible options just if like the user had entered the value.

I ended up using this hack (which it is probably unsupported):

var $selectize = $("#my_input").selectize(/* settings with load*/);
var selectize = $select[0].selectize;
// get the search from the remote server
selectize.onSearchChange('my value');
// enter the input in the input field
$selectize.parent().find('input').val('my value');
// focus on the input field, to make the options visible
$selectize.parent().find('input').focus();
Ickes answered 5/12, 2017 at 14:52 Comment(0)
P
1
var $select = $(document.getElementById("selectTagName"));
var selectize = $select[0].selectize;
selectize.setValue(selectize.search("My Default Value").items[0]);
Plasm answered 16/3, 2020 at 7:54 Comment(0)
F
0

First load select dropdown and then selectize it. It will work with normal $(select).val().

Fluorescence answered 22/11, 2017 at 13:45 Comment(0)
F
0

Here is the simples and quickest way:

$('select[name^=items]').selectize({
    items: ['item1'],        //  Selected  Items
    options: [               //  Preset    Items
        {'value' => 'item1', 'text' => 'item1'},
        {'value' => 'item2', 'text' => 'item2'}
    ],
});
Financier answered 7/4 at 8:42 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.