Sunday, May 19, 2024
 Popular · Latest · Hot · Upcoming
170
rated 0 times [  171] [ 1]  / answers: 1 / hits: 134186  / 10 Years ago, sat, february 22, 2014, 12:00:00

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.


More From » jquery

 Answers
6

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

[#72366] Friday, February 21, 2014, 10 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
darennevina

Total Points: 422
Total Questions: 128
Total Answers: 105

Location: Comoros
Member since Tue, Mar 14, 2023
1 Year ago
;