Me Unagi
Me Unagi

Reputation: 625

Setting listbox value with different value and label upon page load

I am trying to set form value upon page load in a dropdown listbox which loads value thru an ajax call. I was suggested the use of addOption in another thread for a different problem but unfortunately that option does not work for me because data id and data name are different in this case and I only get data Id when the form is rendered. I have noticed addOption code gets executed before the ajax request sends data back.

Following are code snippets from the project. Is there a way to set the value after ajax request is complete?

HTML

<select name="country" placeholder="Please Select Country  ..."></select>

Data population, JavaScript code

$('[name="country"]').selectize({
    valueField: 'id',
    labelField: 'name',
    searchField: 'name',
    preload: true,
    create: false,
    render: {
        option: function(item, escape) {
            return '<div>' + escape(item['name']) + '</div>';
        }
    },

    load: function(query, callback) {
        $.ajax({
            url: '/countrydata',
            type: 'GET',
            error: function() {
                callback();
            },
            success: function(res) {
                callback(res);
            }
        });
    },
});

Data returned by Ajax call

id name
1  USA
2  China
3  Japan

Following is my value setting code which I want to work

$('[name="country"]').selectize();
$('[name="country"]')[0].selectize.setValue(3);

Had the valueField and labelField be the same, I could have used following addOption method as suggested in another post but as I am only getting Id upon form render, I cannot use the following code.

var item  = {};
item.id   = countryName;
item.name = countryName;

$('[name="country"]')[0].selectize.addOption(item);

Upvotes: 4

Views: 714

Answers (2)

davcs86
davcs86

Reputation: 3935

You can use this function based on the source code of selectize.js

function setSelectizeValue(selector, value){
    var select = $(selector)[0].selectize;
    // from the lines 1731-1737 of selectize.js
    select.lastQuery = null;
    select.setTextboxValue("");
    select.addItem(value);
    select.setActiveOption(select.getOption(value));
}

eg.

HTML

<select name="country" placeholder="Please Select Country  ..."></select>
<br/>
<button id="select-usa">Select USA</button>
<button id="select-china">Select China</button>
<button id="select-japan">Select Japan</button>

JS

$('[name="country"]').selectize({
    valueField: 'id',
    labelField: 'name',
    searchField: 'name',
    preload: true,
    create: false,
    render: {
      option: function(item, escape) {
        return '<div>' + escape(item['name']) + '</div>';
      }
    },

    load: function(query, callback) {
        var res = [{"id":1,"name":"USA"},{"id":2,"name":"China"},{"id":3,"name":"Japan"}];
        callback(res);
    },
  });

$("#select-usa").click(function(ev){
    setSelectizeValue('[name="country"]',1);
});
$("#select-china").click(function(ev){
    setSelectizeValue('[name="country"]',2);
});
$("#select-japan").click(function(ev){
    setSelectizeValue('[name="country"]',3);
});

JSFiddle demo

Upvotes: 0

Selfish
Selfish

Reputation: 6200

You can use load method to set options via selectize.js programmatic API. Consider calling clear() and clearOptions() methods to reset selected values and old options as well.

For simplification purposes only, let's give our input an id:

<select id="country" name="country" placeholder="Please Select Country  ..."></select>

Assuming the AJAX response is:

id name
1  USA
2  China
3  Japan

Which is equal to having:

var responseText = "id name\n1  USA\n2  China\n3  Japan"

Let's split the value, and reformat it into a object selectize likes:

var selectizeContent = [];
// Every line will have one value:
responseText.split('\n').forEach(function(line){
    // split current line to id and value:
    var parts = line.split(' ');
    // Verify that ID is numeric, to skip the first line:
    if(!isNaN(parseInt(parts[0]))){
        selectizeContent.push({
            value: parts[0],
            text: parts[1]
        });
    }
});

And then once we have selectizeContent ready:

// Using the ID we gave the select, or any other selector:
var selectize = $("#country")[0].selectize;
selectize.clear();
selectize.clearOptions();
selectize.load(function(callback) {
    callback(selectizeContent);
});

Perform everything we just did inside your Ajax callback, and I expect it'll work.


selectizeContent should be an array of objects that have properties configured in valueField and labelField options when select was initialized. For example, here is how selectizeContent should look like with default valueField and labelField options:

var inviteList = [
    {
        text: 'USA',
        value: 1
    },
    {
        text: 'China',
        value: 2
    },
    {
        text: 'Japan',
        value: 3
    }
];

Upvotes: 1

Related Questions