javascript - select2 jquery x-editable 未设置值 - 单个值

标签 javascript jquery twitter-bootstrap x-editable

我有一个脚本,它执行ajax调用并使用x-editable和select2设置值,当我从加载的列表中选择数据并单击“确定”时,用户界面上的数据没有更新,它一直说它是空的。

这是我的函数

  $('#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);
       }
   });

最佳答案

X-editable 期望您的 ajax 数据以 json 格式返回:

{id: 1, text: "myexample"}

text 键显示在用户界面上。 id 键在提交时发送到服务器。

如果您的 ajax 调用返回的信息偏离上述标准,您必须在 results 函数中重新格式化数据。

下面是一个完整的示例,您可以使用它在 ajax 模式下运行 select2:

$('#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()});
        }                    
    }
})

关于javascript - select2 jquery x-editable 未设置值 - 单个值,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23020434/

相关文章:

javascript - 如何按月、日和年对 <li> 进行排序

css - 在响应式 Bootstrap 导航栏中居中内容

javascript - HTML5 日期时间组件在浏览器中不起作用

jquery - 动态改变div之间的页面内容?

javascript - 单击时按 Angular 图标更改顺序

javascript - 尝试运行 Selenium 时出现问题

javascript - 无法从代码隐藏设置 div 样式

javascript - 将 jquery datepicker 添加到使用 document.createElement() 创建的输入文本框

javascript - 当达到计数 div 中的滚动点时,计数将开始

javascript - 将类添加到 float 框弹出窗口,单击打开弹出窗口