Setting a list value with a different value and label when loading a page

I am trying to set the value of a form when loading a page in a drop down list that loads the value through an ajax call. I was asked to use addOption in another thread for another problem, but unfortunately this parameter does not work for me, because the data identifier and data name are different in this case, and I only get Id data when rendering the form. I noticed that addOption code runs before the ajax request sends the data back.

The following are snippets of code from a project. Is there a way to set the value after the ajax request completes?

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 an Ajax call

id name
1  USA
2  China
3  Japan

Below is my setup code I want to work

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

Field labelField , addOption, , Id , .

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

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

selectize.js API. clear() clearOptions() reset .

id:

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

, AJAX:

id name
1  USA
2  China
3  Japan

:

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

, :

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]
        });
    }
});

, selectizeContent :

// 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);
});

, Ajax, , .


selectizeContent , , valueField labelField, . , selectizeContent valueField labelField:

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

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));
}

.

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

0

Source: https://habr.com/ru/post/1606084/


All Articles