usearch
usearch

Reputation: 75

select2 jquery x-editable not setting value - single value

I have script which does ajax call and sets values using x-editable and select2, when I select data from list which is loaded and click ok the data is not updated on UI, it keep saying it is empty.

Here is my function

  $('#ActFilter').editable({
       type: 'select2',
       title: 'Act',
       placement: 'right',
       select2: {
         cacheDataSource: false,

           allowClear: true,
           multiple: false,
           tokenSeparators: [",", " "],
           minimumResultsForSearch: 1,
           initSelection: function (element, callback) {
               return $.get('rest/qualityActsCode', {
                   query: element.val()
               }, function (data) {
                   self.cacheDataSource = data;

                   if (element.val() != "") {
                       var id = element.val();
                       filteredData = new Array();
                       for (var i = 0; i < data.length; i++) {
                               if (data[i].id == id) {
                                 filteredData.push(data[i]);
                                   break;
                               }
                       }
                       callback(filteredData);

                   }
               });
           },
           query: function(query) {
               self = this;
               var key = query.term;
               var cachedData = self.cacheDataSource;

               if(cachedData) {
                   query.callback({results: cachedData});
                   return;
               } else {
                   $.ajax({
                     url: 'rest/qualityActsCode',
                     data: { q : query.term },
                     dataType: 'json',
                     type: 'GET',
                     success: function(data) {
                       self.cacheDataSource = data;
                       query.callback({results: data});
                     }
                   });
               }
           }
       },
       url: function (a, v) {
           $('#ActValue').val(a.value);
       }
   });

Upvotes: 1

Views: 6417

Answers (2)

Arief Suherlan
Arief Suherlan

Reputation: 21

There is issue on x-editable using select2 latest version. i suggest you use version 4.0.0 of select2. refer to this link: https://github.com/vitalets/x-editable/issues/882

Upvotes: 1

Mysteryos
Mysteryos

Reputation: 5791

X-editable expects your ajax data to be returned in the json format of:

{id: 1, text: "myexample"}

The text key is displayed on the ui. The id key is sent to the server on submit.

In case, your ajax calls returns information that deviates from the above standard, you have to reformat the data in the results function.

Below is a full blown example that you can use to run select2 in ajax mode:

$('#my-x-editable-element').editable({
    //If there is no selected item, the placeholder will be displayed on the select2 element
    placeholder: "Select a customer",

    //Send data to server, upon submit (i.e on click of the tick button)
    onblur: 'submit',

    //VERY IMPORTANT: set to the url where you will fetch the data.
    //The request URL to the server would then be the following format: "/ajaxsearch/customercode?term=searchtext&limit=10&page=1&_=1440047016963"
    //Parameter explanation(can be customized in the data section below):
    //Term = the term typed in the select2 box. Use this value to search your database
    //Limit = How many items select2 is expecting in your return call. Use this to limit your query results
    //Page = select2's current page. Use this value to calculate the offset of your query.
    source: '/ajaxsearch/customercode',

    //Define your select2 options, It is compatible with most select 3.x options
    select2: {
        allowClear: false,
        minimumInputLength: 3,
        //IMPORTANT: set the id from your ajax result.
        id: function (item) {
            return item.id;
        },
        //IMPORTANT: Customize your ajax calls
        ajax: {

            //Url to the ajax call. Notice that it is the same as the 'source' option above. Both have the same purpose. Don't ask why.
            url: "/ajaxsearch/customercode",

            //Data type you are expecting in return
            dataType: "json",

            //The amount of time after typing a new term, that select2 will wait, before sending a new ajax request
            quietMillis: 500,

            //Query parameters send to the server on ajax calls. Customize as necessary.
            data: function (term, page) {
                return {
                    term: term,
                    limit: 10,
                    page: page
                };
            },

            //IMPORTANT
            //Results function: Used to customize the array of data received from the server.
            //@param {data} array response from the ajax call
            //@param {page} int current page number - select2 pagination
            //@return {object}
            //return value X-editable, expected two keys at the top level of the array: 'results' and 'more'
            //'results' is an array of items from your recent query.
            //'more' is a boolean. It informs x-editable if there is more information that can be queried from your database. If it is true, select2 will send a new query to the database while scrolling the list of items.

            results: function (data, page){

                //Calculation to determine if there is more information that can be queried
                //Based on the total count of rows from the database, current page, and limit of items per page(in this case, 10).
                var more = (page * 10) < data.total

                //If query returned some results, we map it in an x-editable compatible format.
                //Array format MUST contain the 'id' and 'text' keys.
                if(data.total > 0)
                {
                    var mycustomarray;
                    mycustomarray = $.map(data.customers, function (item) {
                        return {
                            id: item.code,
                            name: item.name,
                            text: item.name+" (Code:"+item.code+")"
                        }
                     });
                    return {results: mycustomarray, more:more};
                }
                else
                {
                    //If there are no results, return empty array, as shown below
                    return {results: ''};
                }
            },
        },

        //IMPORTANT
        //Format Selection function
        //Used for display purposes, i.e the text that x-editable shows after the x-editable has been submitted.
        //If x-editable fails to get the text, 'empty' will be shown on submit.
        //@param {object} item currently selected item on the select2 list
        //@return {string}

        formatSelection: function (item) {
            return item.text;
        },

        //Init Selection function
        //Used for initializing the x-editable object if there is already a value present on document load.
        //@param {object} element jQuery current x-editable element
        //@param {function} callback function to set default values

        initSelection: function (element, callback) {
            callback({id: element.val() , text: element.parents('div.editable-select2').children('a.editable').html()});
        }                    
    }
})

Upvotes: 2

Related Questions