How to get the value of the currently selected Selectize.js input item
Asked Answered
B

5

38

I was wondering, how could I get the value of the currently selected item in my Selectize.js input? I have checked the documentation and scoured everything selectize.js related on Stackoverflow but found nothing in the way of an example I could go off of. Any ideas? Here is what I figured would work based on the documentation, but instead gave me Undefined is not a function error.

Please note the very bottom of the code, where I use the select.on('change'; this (in addition to other API methods) is what I have tried. The on change works perfectly, but unfortunately nothing else has.

var select = $('#searchTextbox').selectize({
          maxItems: 1, //Max items selectable in the textbox
          maxOptions: 30, //Max options to render at once in the dropdown
          searchField: ['text'], //Fields the autocomplete can search through.  Example of another searchable field could be 'value'
          openOnFocus: true,
          highlight: true,
          scrollDuration: 60, //currently does nothing; should say how many MS the dropdown and drop up animations take
          create: false, //Whether or not the user is allowed to create fields
          selectOnTab: true,
          render: {
              option: function(data, escape) {
                  var valueArray = [];         
                  valueArray[0] = data.value.split(",");
                  var color = valueArray[0][0] == "1" ? "green" : "red";

                  return '<div class="option" style="color: ' 
                      + color 
                      + ';">' 
                      + escape(data.text) 
                      + '</div>';
              },
              item: function(data, escape) {
                  var valueArray = [];         
                  valueArray[0] = data.value.split(",");
                  var color = valueArray[0][0] == "1" ? "green" : "red";

                  return '<div class="option" style="color: ' 
                      + color 
                      + ';">' 
                      + escape(data.text) 
                      + '</div>';
              }      
          }
      });

select.on('change', function() {
      var test = select.getItem(0);
      alert(test.val());
});

Baldachin answered 10/7, 2014 at 1:51 Comment(1)
To get value and text see my answer here: https://mcmap.net/q/410603/-get-text-from-selected-using-selectizeMarquee
B
42

Found the problem!

For anyone using selectize.js and having problems with the API, try this!

If you look at the part of the code where I initialized the selectize.js dropdown, I store the instance in my 'select' variable and that's it. However, this isn't the proper way to do things (from what I've seen at least). You need to do the following, rather than simply just storing the instance in a variable.

var $select = $("#yourSelector").selectize({
    //options here
});

var selectizeControl = $select[0].selectize

After you do this, you can use the API properly. Without doing it this way, I was getting an Undefined is not a function error.

Finally, to answer my own question, I was able to retrieve the current value of the selectize input by using the following code (the .on('change') and alert are obviously not necessary):

selectizeControl.on('change', function() {
      var test = selectize.getValue();
      alert(test);
});

Why it's necessary to do it this way I'm not exactly sure. Perhaps someone could enlighten me and any future viewers as to why this way works and my previous method didn't.

I hope this helps someone else out in the future. Feel free to edit and make any changes.

Baldachin answered 10/7, 2014 at 4:36 Comment(5)
var something = selectizeControl.getItem(selectizeControl.getValue()).text();Albertina
Full version for direct access in the console: $('#yourSelector').selectize()[0].selectize.getValue()Sexagesima
The two options are: 1) Store the object reference in a variable, which you load into code anywhere you go 2) The call in the comment above, which resets your settings since .selectize() initializes Is there a better third option to get the reference without storing it or resetting it?Vaclava
The option I'm using, which generally seems to work, is to store the reference in $(selectObject).data("selectize") so I can retrieve it elsewhere in code without expanding the scope of the reference. $selectize = $("#mySelect").selectize({ .... }); $("#mySelect").data("selectize", $selectize); ... $selectize = $("#mySelect").data("selectize"); $libraryObject = $selectize[0].selectize;Vaclava
Thank you @JasonBeck, that worked. Though it seems like a workaround. It should be some way to get a reference to a selectize without reinitalizing it.Obmutescence
I
35

Rather than attaching the event later, you can do it in the initialization:

var select = $('#searchTextbox').selectize({
          maxItems: 1, //Max items selectable in the textbox
          maxOptions: 30, //Max options to render at once in the dropdown
          ...
          onChange: function(value) {
               alert(value);
          }
      });

Check out the docs for more callbacks.

Inhere answered 13/1, 2015 at 21:33 Comment(0)
M
6

In my testings, selectize imediatelly updates the value of the <select> it 'replaced' (actually it only hides the <select> using display: none).

So if you don't want to use callbacks neither global variables, it's as simple as:

$('#id_of_the_select_element_you_called_selectize_on').val().

Mechellemechlin answered 16/8, 2017 at 0:47 Comment(1)
The simple id selector (#) might not work, but the simple class selector (.) will. If you would rather not use class and stick with id, use the attribute selector, as in $('select[id="id_of_the_select_element_you_called_selectize_on"] option').val(). See more in my answer to a similar question: #25091071Merline
M
0

In my case the above answers didn't worked, but I figured out a simple solution.

$("select").on('change', function() {
  var val = $(this).find(".item").attr('data-value');
  alert(val);
});
Mcconaghy answered 4/2, 2021 at 17:6 Comment(0)
N
0

I've worked with an input-group-button, like this:

HTML

<div class="input-group">
    <div class="input-group-button">
        <button type="button" class="button clear hide clear-selectize" value="clear">
            <span>X</span>
        </button>
    </div>
    <select name="name" id="id" class="selectize">
        <option value="">Choose an option</option>
        <option value="value1">value1</option>
        <option value="value2">value2</option>
        <option value="Value3">Value3</option>
    </select>
</div>

jQuery

var $selectize = jQuery('.selectize').selectize({
    persist: false,
    create: true,
    sortField: 'text',
    onChange: function (value) {
        checkSelectizeValue(value);
    }
});

function checkSelectizeValue(value) {
    if ($('.selectize').val() !== '') {
        $('.clear-selectize').removeClass('hide');
    } else {
        $('.clear-selectize').addClass('hide');
    }
}

jQuery(document).on("click", ".clear-selectize", function (e) {
    var selectize = $selectize[0].selectize;
    selectize.clear();
});
Neckerchief answered 18/2, 2021 at 13:6 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.