Logan Voss
Logan Voss

Reputation: 69

How to set values of selectized fields with results from ajax?

I've seen tons of threads on how to set a default value for select boxes I selectize, but how do you set the value of a selectized select box with the value I get back from an ajax call?

My function looks like this:

$('#import_search').change(function(){
    $.ajax({ 
        url: 'import_ajax.php',
        type: 'POST',
        data: { import_search: $('#import_search option:selected').val() },
        dataType: 'text',
        timeout: 60000,
        success: function(data) {
            var result = JSON.parse(data);  
            var project = result['selected_project'];
            $.each(result.data[0], function(key, value) { 
                $('#' + key).val(value);
         ->   //$('#' + whatever the new selectize ID is).setValue(value from db)
            });
        }
    }); 
});


....
//selectize the select boxes
$('#Customer').selectize({
    create: true,
    sortField: 'text'
});

I made it easy because the IDs of my fields match the column names in the database,

I.E the $('#' + key).val(value); line.

So when I get something back that has a Customers key, how do I set the value of the selectized customers select box to the value I get back from the ajax call?

The select boxes are selectized on load and are populated correctly from stuff from the database, this is a function to "import" settings from a previous project and pre-set everything for the user based on the selected project.

I'm not looking to add any new values, the values will already be in the selectized select boxes as "options", all I need to do is set them to what I get from the ajax call, they will always have a match because they're initially set from queries to the db.

I've tried setValue() but I'm not sure I'm doing it right. Please help!

This is a question specifically about the selectize jquery add-on, selectize changes the class, id, lots of things on whichever specific field. It's not the same question as the one proposed as a duplicate.

-EDIT- I've modified my script, here's what I have so far.

$(document).ready(function(){
    $('#import_search').change(function(){
        var $select = $('#Customer').selectize();
        var selectize = $select[0].selectize;
        $.ajax({ 
            url: 'import_ajax.php',
            type: 'POST',
            data: { import_search: $('#import_search option:selected').val() },
            dataType: 'text',
            timeout: 60000,
            success: function(data) {
                var result = JSON.parse(data);  
                var project = result['selected_project'];
                $.each(result.data[0], function(key, value) { 
                    $('#' + key).val(value);
                    if (selectizeInstances[key]) {
                        alert(selectizeInstances[key]);
                        selectizeInstances[key].setValue(value);
                    }
                });
            }
        });
    });     
    var selectizeInstances = [];
    var selectizeControl = $('#Customer').selectize({
        create: true,
        sortField: 'text'
        });
    selectizeInstances['Customer'] = selectizeControl[0].selectize; 
});

Upvotes: 0

Views: 2414

Answers (1)

Sᴀᴍ Onᴇᴌᴀ
Sᴀᴍ Onᴇᴌᴀ

Reputation: 8297

Ensure that the $('#import_search').change(function(){... happens after the DOM is ready (e.g. in the callback function for $(document).ready().

To call setValue() on the selectize control, it appears we need to capture an instance of the control. Per the api documentation, we can do this like in the following example:

var selectizeInstances = [];
var selectizeControl = $('#Customer').selectize({
    create: true,
    sortField: 'text'
});
selectizeInstances['Customer'] = selectizeControl[0].selectize;

Then replace the line:

//$('#' + whatever the new selectize ID is).setValue(value from db)

With a check like this:

if (selectizeInstances[key]) {
    selectizeInstances[key].setValue(value);
}

Try this plunker - change the search method select list to see the value of the Customer select input changed.

Or this example should demonstrate the technique, but without the AJAX requestion:

$(document).ready(function() {
  $('#import_search').change(function() {
    var index = $(this).val();
    Array.prototype.forEach.call(Object.keys(selectizeInstances), function(key) {
      var indexOptions = Object.keys(selectizeInstances['Customer'].options);
      if (selectizeInstances[key]) {
        var value = indexOptions[index];
        $('#' + key).val(value);
        selectizeInstances[key].setValue(value);
      }
    });
  });
  //store the reference to the selectize control in an array so it can be utilized dynamically later:
  var selectizeInstances = [];
  var selectizeControl = $('#Customer').selectize({
    create: true,
    sortField: 'text'
  });
  selectizeInstances['Customer'] = selectizeControl[0].selectize;
});
<link href="//cdnjs.cloudflare.com/ajax/libs/selectize.js/0.9.0/css/selectize.default.css" rel="stylesheet" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="//cdnjs.cloudflare.com/ajax/libs/selectize.js/0.9.0/js/standalone/selectize.js"></script>
<div>
  Search method:
  <select id="import_search">
    <option value="0">0</option>
    <option value="1">1</option>
    <option value="2">2</option>
  </select>
</div>

Customer:
<select id="Customer">
  <option value="cat">Cat</option>
  <option value="dog">Dog</option>
  <option value="rat">Rat</option>
</select>

Upvotes: 1

Related Questions