Select2从上次选择的选择框中检索无效结果

时间:2013-05-13 13:14:20

标签: javascript jquery jquery-select2

我目前正遇到一个问题,我的select2插件有时显示上次选择的选择框的结果。另外,当我第一次点击选择框或输入太快时,我也会得到g.results为null。我的代码如下。

        window.currentField = ""; //current product field data
        window.currentCategory = "";   //current product category data

        //lets get some data from the hidden input for providing suggestions via ajax

        $(".suggestive-entry").live('click',function() {
            //alert("click called");
            //alert("test");

            window.currentField = $(this).siblings('input:hidden').attr('data-field'); //get the field attribute
           // alert(window.currentField);
            window.currentCategory = $(this).siblings('input:hidden').attr('data-category'); //get the category attribute
        });

        //formats select2 returned option
        function format(item) { return item.term; };

        //used for suggestive search fields
        $(".suggestive-entry").select2({
            createSearchChoice:function(term, data) { if ($(data).filter(function() { return this.term.localeCompare(term)===0; }).length===0) { return {id:term, term:term};} },
            initSelection : function (element, callback) {
                var data = {id: element.val(), term: element.val()};
                callback(data);
            },
            multiple: false,
            ajax: {
                url: "includes/ajax/map-fields.php",
                dataType: 'json',
                data: function (term, page) {
                    //alert("suggestive called");
                    return {
                        q: term,
                        field: window.currentField,
                        ptype: window.currentCategory
                    };
                },
                results: function (data, page) {
                    return { results: data };
                }
            },

            formatSelection: format,
            formatResult: format
        });

非常感谢任何帮助。

1 个答案:

答案 0 :(得分:1)

尝试为你的隐藏字段提供id,做这样的事情

   data: function (term, page) {
        //alert("suggestive called");
        var data_field = $('#someId').attr('data-field');
        var data_category = $('#someId').attr('data-category');
        return {
                q: term,
                field: data_field,
                ptype: data_category
            };
    }