JqGrid searchoptions with select2 existing value

ぐ巨炮叔叔 提交于 2019-12-11 09:41:19

问题


I'm trying to integrate select2 for JqGrid filter form. I'm using JqGrid min 4.6 & Select2 min 4.0.1. The filter works fine but I'm unable to retrieve the value that has been set through select2 once the filter form is closed and reopened. i.e. dataInit e1 does not return the existing value of the select input. I must be doing something wrong?

JqGrid Column Model:

        {
            name: 'CurrencyID', hidden: true, search: true, stype: 'select', searchtype: 'number', searchoptions: {
                searchhidden: true,
                sopt: ['eq', 'ne'],
                dataInit: function (el) {
                    intiGridFilterSelecr2Field(el, paramFromView.CurrencyOptions);
                }
            },
            searchrules: { required: true }
        },

Parameters:

@section scripts{
<script>
   var paramFromView = {
        CurrencyOptions: {
            searchURL: '@Url.Action("GetCurrency", "Controller")',
            detailURL: '@Url.Action("CurrencyDetailsJson", "Controller")',
            idField: 'CurrencyID',
            txtField: 'Description'
        }
   };
</script>
}

Select2 Helper:

function intiGridFilterSelecr2Field(element, options) {
var comboPageSize = 15;
var quietMillis = 200;
var placeHolderText = 'Choose...'

var defaults = {
    searchURL: '',
    detailURL: '',
    idField: '',
    txtField: ''
};
var options = $.extend({}, defaults, options);
var select2Element = $(element);

select2Element.select2({
    width: 'element',
    minimumInputLength: 1,
    placeholder: placeHolderText,
    ajax: {
        url: options.searchURL,
        dataType: 'json',
        quietMillis: quietMillis,
        cache: false,
        data: function (params) {
            return {
                name: params.term,
                page: params.page,
                pageSize: comboPageSize
            };
        },
        processResults: function (data) {
            var more = (data.page * comboPageSize) < data.total;

            var resultsArr = [];
            for (var i = 0; i < data.result.length; i++) {
                resultsArr.push({ id: data.result[i][options.idField], text: data.result[i][options.txtField] });
            }
            return { results: resultsArr, more: more };
        }
    },
}).each(function (index, element) {
    var idCombo = $(this);
     // The problem is that idCombo.val() is always empty.
     // element:select2-hidden-accessible
    if (idCombo.val() != null && idCombo.val().length > 0) {
        $.ajax(options.detailURL, {
            data: {
                id: idCombo.val()
            },
            dataType: 'json',
            cache: false
        }).done(function (data) {
            var optselected = select2Element.find('option').filter(function () { return this.value == data[idField] && this.text == data[txtField] && this.selected })
            if (optselected == undefined || optselected.length == 0) {
                var $optionContact = $("<option selected></option>").val(data[idField].toString()).text(data[txtField]);
                var toBeRemoved = select2Element.find('option').filter(function () { return this.value == data[idField] });
                if (toBeRemoved != undefined) {
                    toBeRemoved.remove();
                }
                select2Element.append($optionContact).trigger('change.select2');
            }
        });
    }

  });
}

When the filter is being set...

When Loading the existing filter. How do I pass this CurrencyID = 1 to select2 helper?

Update:

With Oleg's answer, I updated my code as below.

            {
            name: 'CurrencyID', hidden: true, searchtype: 'number', search: true,
            stype: "select", searchoptions: {
                searchhidden: true,
                sopt: ["eq", "ne"],
                dataUrl: paramFromView.CurrencyOptions.searchURL,
                buildSelect: function (data) {
                    var obj = jQuery.parseJSON(data);
                    var i, options = [];
                    for (i = 0; i < obj.result.length; i++) {
                        options.push("<option value='" + obj.result[i][paramFromView.CurrencyOptions.idField] + "'>" +
                            obj.result[i][paramFromView.CurrencyOptions.txtField] + "</option>");
                    }
                    return "<select>" + options.join("") + "</select>";
                },
                noFilterText: "Any",
                selectFilled: function (options) {
                    setTimeout(function () {
                        $(options.elem).select2({
                            width: 'element',
                        });
                    }, 0);
                }
            },
            searchrules: { required: true }
        },

I'm almost there with what I wanted to achieve. However I'm still facing some difficulties.

  1. When the filter is initially loaded, value is selected on the dropdown but query value is empty. i.e. if the user clicks on the find button soon after the filter form is loaded, no filter will be set.

  2. I still cannot get select2 styles working.


回答1:


I can demonstrate how to use select2 with free jqGrid fork of jqGrid, which I develop. I get the demo from the README of the old version 4.14.1 (the current released version is 4.15.3) and modified it to demonstrate the usage of select2.

The main part of the code could be

stype: "select",
searchoptions: {
    sopt: ["eq", "ne"],
    ...
    selectFilled: function (options) {
        setTimeout(function () {
            $(options.elem).select2({
                width: "100%"
            });
        }, 0);
    }
}

See https://jsfiddle.net/Lae6kee7/2/. You can try to choose an option in the filter toolbar in "Shipped via" column and the open the search dialog. You will see that the select2 will have the same option selected.

If you would load the data via Ajax request posted by select2 than your code will be much more complex as it could be. It's important to understand that such way is really required only for really large set of possible value. I means the number of items larger as 100000 items for example. On the other side, the most use cases required less as 1000 options. In the case it would be more effective to load all the data as options of select and then convert the select to select2. select2, which uses local select works much more quickly from the users point of view.

The code will be easier in my opinion if you will use dataUrl instead of ajax option of select2. You can use dataUrl to return from the server all different values, which can be used in select2 and to use buildSelect to build <select> from JSON data returned from the server. The demo https://jsfiddle.net/Lae6kee7/23/ demonstrates that. I made the demo for JSFiddle, which supports Echo service (see here), which allows to simulate server responses. Your real code should contains mostly only dataUrl, buildSelect and the code of selectFilled, which I included above.

Additionally, I'd recommend you to consider to use <datalist> (see here for example), which could be good alternative to select2. All modern web browsers contains native support of <datalist> and thus <datalist> works very quickly. Try to search in the first Client column of my demos. You will see control, which will be very close to select2. Additional advantage of <datalist>: one will be able not search for only exact predefined values like test10, test11 or test12, but for substrings like 1. Compare

with

or

with



来源:https://stackoverflow.com/questions/49283029/jqgrid-searchoptions-with-select2-existing-value

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!