free-jqgrid: mutliselect in free-jqgrid 4.14.0

2019-09-06 23:10发布

问题:

Not sure why the multi-select is not working when I select more then one value. I am using free-jqgrid 4.14.0 and multiselect js from erichynds. Also the multi-select is not coming as drop down. Am I missing any CSS or anything...

Any help please...

Created fiddle, but since I can't access fiddle at my workplace, I used my cell phone, so it is not working now. I must have missed something. https://jsfiddle.net/SudhirSahoo/h2k1ok2u/

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="utf-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <title>SKumar - JQGrid</title>
    <meta name="author" content="SK Inspired from Oleg">
    <link rel="stylesheet" href="http://ajax.googleapis.com/ajax/libs/jqueryui/1.11.4/themes/redmond/jquery-ui.min.css">
    <link rel="stylesheet" href="http://netdna.bootstrapcdn.com/font-awesome/4.4.0/css/font-awesome.min.css">
	<link rel="stylesheet" href="http://www.ok-soft-gmbh.com/jqGrid/jquery-ui-multiselect/1.13.6/jquery.multiselect.css" />
    <!--<link rel="stylesheet" href="jqGrid/css/ui.jqgrid.css">-->
    <link rel="stylesheet" href="http://rawgit.com/free-jqgrid/jqGrid/master/css/ui.jqgrid.css">
	
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
	<script src="https://code.jquery.com/ui/1.12.1/jquery-ui.js"></script>
	<script type="text/javascript" src="http://www.ok-soft-gmbh.com/jqGrid/jquery-ui-multiselect/1.13.6/jquery.multiselect.js"></script>
    <style type="text/css">
        html, body { font-size: 75%; }
		#gridSearchResult {
			height: 460px;
		}
    </style>
    <script type="text/javascript">
        $.jgrid = $.jgrid || {};
        $.jgrid.no_legacy_api = true;
        $.jgrid.useJSON = true;
    </script>
    <!--<script src="http://rawgit.com/free-jqgrid/jqGrid/master/js/jquery.jqgrid.src.js"></script> -->
	<script src="https://rawgit.com/free-jqgrid/jqGrid/master/js/jquery.jqgrid.src.js"></script>
    <!--<script src="jqGrid/js/jquery.jqGrid.src.js"></script>-->
    <script type="text/javascript">
    //<![CDATA[
        /*global $ */
        /*jslint eqeq: true, browser: true, plusplus: true */
        $(function () {
            "use strict";
            var $grid = $("#list"),
                gridData,
                startTime,
                measureTime = false,
                timeInterval,
				myDefaultSearch = "cn",
                getColumnIndexByName = function (columnName) {
                    var cm = $(this).jqGrid('getGridParam', 'colModel'), i, l = cm.length;
                    for (i = 0; i < l; i += 1) {
                        if (cm[i].name === columnName) {
                            return i; // return the index
                        }
                    }
                    return -1;
                },
                modifySearchingFilter = function (separator) {
                    var i, l, rules, rule, parts, j, group, str, iCol, cmi, cm = this.p.colModel,
                        filters = $.parseJSON(this.p.postData.filters);
                    if (filters && typeof filters.rules !== 'undefined' && filters.rules.length > 0) {
                        rules = filters.rules;
                        for (i = 0; i < rules.length; i++) {
                            rule = rules[i];
                            iCol = getColumnIndexByName.call(this, rule.field);
                            cmi = cm[iCol];
                            if (iCol >= 0 && ((typeof (cmi.searchoptions) === "undefined" ||
                                  typeof (cmi.searchoptions.sopt) === "undefined")
                                 && rule.op === myDefaultSearch) ||
                                    (typeof (cmi.searchoptions) === "object" &&
                                        $.isArray(cmi.searchoptions.sopt) &&
                                        cmi.searchoptions.sopt[0] === rule.op)) {
                                // make modifications only for the 'contains' operation
                                parts = rule.data.split(separator);
                                if (parts.length > 1) {
                                    if (typeof filters.groups === 'undefined') {
                                        filters.groups = [];
                                    }
                                    group = {
                                        groupOp: 'OR',
                                        groups: [],
                                        rules: []
                                    };
                                    filters.groups.push(group);
                                    for (j = 0, l = parts.length; j < l; j++) {
                                        str = parts[j];
                                        if (str) {
                                            // skip empty '', which exist in case of two separaters of once
                                            group.rules.push({
                                                data: parts[j],
                                                op: rule.op,
                                                field: rule.field
                                            });
                                        }
                                    }
                                    rules.splice(i, 1);
                                    i--; // to skip i++
                                }
                            }
                        }
                        this.p.postData.filters = JSON.stringify(filters);
                    }
                },
                dataInitMultiselect = function (elem) {
                     setTimeout(function () {
                         var $elem = $(elem), id = elem.id,
                             inToolbar = typeof id === "string" && id.substr(0,3) === "gs_";
                             options = {
                                 selectedList: 2,
                                 height: "auto",
                                 checkAllText: "All",
                                 uncheckAllText: "None",
                                 noneSelectedText: "Any",
                                 open: function () {
                                     var $menu = $(".ui-multiselect-menu:visible");
                                     $menu.width("auto");
                                     return;
                                 }
                             };
                         if (inToolbar) {
                             options.minWidth = 'auto';
                         }
                         $elem.multiselect(options);
                         $elem.siblings('button.ui-multiselect').css({
                             width: inToolbar? "98%": "100%",
                             marginTop: "1px",
                             marginBottom: "1px",
                             paddingTop: "3px"
                         });
                     }, 50);
                 };


            var date = new Date(), t = Object.prototype.toString.call(date), t1 = String(date);

			$( "#search" ).click(function() {
				var statesAsString = getStates();
				startTime = new Date();
				$grid.jqGrid({
					datatype: 'json',
					url: 'https://api.myjson.com/bins/efhbt',
					mtype: 'GET',
							colNames: ['aa', 'bb', 'cc', 'dd', 'ee', 'ff', 'gg', 'hh', 'ii', 'Priority', 'Due Date', 'll', 'mm'],
					colModel: [
						{ name: "aa", width: 200, label: "c01", frozen: true },
						{ name: "bb", width: 200, label: "c02", frozen: true },
						{ name: "cc", width: 100, label: "c03", frozen: true, search: true,
							stype:'select', 
								searchoptions: {
									 sopt: ['eq','ne'],
									 value: statesAsString,
									 attr: {multiple: 'multiple', size: 3},
									 dataInit: dataInitMultiselect
								 }
						},
						{ name: "dd", width: 100, label: "c04" },
						{ name: "ee", width: 100, label: "c05" },
						{ name: "ff", label: "c06" },
						{ name: "gg", label: "c07", editable: true, stype: 'select', formatter: 'select',
							edittype: 'select', editoptions: {
								value: 'Select:Select;Y:Yes;N:No',
								multiple: false
							}
						},
						{ name: "hh", label: "c08", editable: true, stype: 'select', formatter: 'select',
							edittype: 'select', editoptions: {
								value: 'Select:Select;Y:Yes;N:No',
								multiple: false
							}
						},
						{ name: "ii", label: "c09", editable: true, stype: 'select', formatter: 'select',
							edittype: 'select', editoptions: {
								value: 'Select:Select;Y:Yes;N:No',
								multiple: false
							}
						},
						{ name: "jj", label: "c10", width: 100, editable: true },
						{ name: "kk", label: "c11", width: 100, editable: true, 
							formatter:'date', formatoptions: {newformat:'Y-m-d'}, datefmt: 'Y-m-d',
							editoptions: {
								size:20, 
								dataInit: function(el){ 
									$(el).datepicker({
										dateFormat: 'yy-mm-dd',
										changeYear: true,
										changeMonth: true,
										showWeek: true,
										yearRange: '1999:+1',
										minDate: new Date()
									}); 
								}, 
								defaultValue: function(){ 
									var currentTime = new Date(); 
									var month = parseInt(currentTime.getMonth() + 1); 
									month = month <= 9 ? "0"+month : month; 
									var day = currentTime.getDate(); 
									day = day <= 9 ? "0"+day : day;
									var year = currentTime.getFullYear();
									return year+"-"+month + "-"+day; 
								},
								maxlength: 10
							},
							searchoptions: {
								sopt: ['eq'],
								dataInit: function (elem) {
									$(elem).datepicker({
										dateFormat: 'yy-mm-dd',
										changeYear: true,
										changeMonth: true,                            
										showWeek: true,
										showButtonPanel: true,
										autoclose: false,
										currentText: "Clear",
										closeText: "Filter",
										yearRange: '1999:+1',
										onSelect: function( selectedDate, inst ) {
											$(this).focus();
											var target = $(selectedDate);
											var inst = this._getInst(target[0]);
											inst.inline = true;
											$.datepicker._selectDateOverload(selectedDate, inst);
											inst.inline = false;
											this._updateDatepicker(inst);
										}
									}).focus(function() {
										var thisCalendar = $(this);
										$('.ui-datepicker-close').click(function() {
											var selectedDate = $("#gs_kk").val();
											setTimeout(function () {
												$('#list')[0].triggerToolbar();
											}, 100);
											
										});
										
										$('.ui-datepicker-current').click(function() {
											var selectedDate = $("#gs_kk").val('');
										});
									});
								}
							}
						},
						{ name: "ll", label: "c12", editable: true },
						{ name: "mm", label: "c13", editable: true }
					],
					cmTemplate: { width: 100, autoResizable: true },
					rowNum: 1000,
					records: 1000,
					rownumWidth: 40,
					rowList: [20, 100, 1000, 10000, "100000:All"],
					viewrecords: true,
					rownumbers: true,
					toppager: false,
					pager: false,
					shrinkToFit: false,
					multiselect: true,
					editurl: 'clientArray',
					loadonce: true,
					width: 800,
					height: 400,
					onSortCol: function () {
						startTime = new Date();
						measureTime = true;
					},
					/*onSelectRow: function (rowid) {
						var $self = $(this),
							savedRow = $self.jqGrid("getGridParam", "savedRow");
						if (savedRow.length > 0) {
							$self.jqGrid("restoreRow", savedRow[0].id);
						}
						$self.jqGrid("editRow", rowid);
					},*/
					loadComplete: function () {
						if (measureTime) {
							setTimeout(function () {
								//alert("Total loading time: " + timeInterval + "ms");
							}, 50);
							measureTime = false;
						}
					},
					autoencode: true,
					caption: "Shows the performance of resizing. Make double-click on the column resizer"
				}).jqGrid("filterToolbar", {
						beforeSearch: function () {
							startTime = new Date();
							measureTime = true;
							return false; // allow filtering
						}
				}).jqGrid("gridResize");
				$grid.jqGrid("setFrozenColumns");
			});
			
			
             timeInterval = new Date() - startTime;
             setTimeout(function () {
                // alert("Total time: " + timeInterval + "ms");
             }, 50);

			


			 // On Click Of Button
			$( "#Change_Value" ).click(function() {
				var v = $("#name").val();
				var myGrid = $("#list");
				var selRowIds = myGrid.jqGrid("getGridParam", "selarrrow");
				//alert(selRowId.length);
				for (var i = 0; i < selRowIds.length; i++) {
					//rowData = myGrid.jqGrid("getLocalRow", selRowIds[i]);
					// one can uses the data here
					myGrid.jqGrid("editRow", selRowIds[i], true);
				}
			});
        });
		
		function getStates() {
			var statesAsString = '';
			$.ajax({
				type 	: "GET",
				url  	: "https://api.myjson.com/bins/xvjhl",
				ContentType : 'json',
				cache: false,
				async: false,
				success	: function (data) {
					var len = data.length;
					for ( var i = 0; i < len; i++) {
						if(!(data[i] == null || data[i].toUpperCase() == 'NULL'))
						{
							statesAsString += data[i] + ':' + data[i]+ ';';
						}
						}	
						statesAsString = statesAsString.slice(0, -1);				
				}
			})
			return statesAsString;
		}
    //]]>
    </script>
</head>
<body>
    <div style="border: 1px solid black; padding-top: 10px; padding-bottom: 10px;">
		<TABLE width="100%">
			<TBODY>
				<TR>
					<TD align=left>
						Country: <input type="text" name="country" id="country" />
						&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
						State: <input type="text" name="state" id="state" />
						&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;
						<input type="button" name="search" id="search" value="Search" />&nbsp;&nbsp;
						
						<input type="button" name="reset" id="reset" value="Reset" />
					</TD>
					<TD align=right>
						<input type="button" name="Change_Value" id="Change_Value" value="Change Priority to High" /> 
					</TD>
				</TR>
			</TBODY>
		</TABLE>
	</div>
	
    <div id='gridSearchResult' style="margin-top: 10px;">
		<table id="list"></table>
    </div>
	<div style="border: 1px solid black; align: centre; margin-top: 10px; padding-top: 10px; padding-bottom: 10px;">
		<TABLE width="100%">
		<TBODY>
			<TR>
				<TD align=center>
					<input type="button" name="save" id="save" value="Save" />&nbsp;&nbsp;
					
					<input type="button" name="submit" id="submit" value="Submit" />
				</TD>
	       	</TR>
		</TBODY>
	</TABLE>
	</div>
</body>
</html>

回答1:

You use very old code example, which I wrote before starting the project free jqGrid. Free jqGrid now support many features, which allows to simplify the code (and to make it working)

The demo https://jsfiddle.net/OlegKi/h0mwtw8s/ uses the following code:

var dataInitMultiselect = function(elem, searchOptions) {
    var $grid = $(this);
    setTimeout(function() {
        var $elem = $(elem),
            id = elem.id,
            inToolbar = searchOptions.mode === "filter",
            options = {
                selectedList: 2,
                height: "auto",
                checkAllText: "all",
                uncheckAllText: "no",
                noneSelectedText: "Any",
                open: function() {
                    var $menu = $(".ui-multiselect-menu:visible");
                    $menu.width("auto");
                    $menu.find(">ul").css("maxHeight", "200px");
                    return;
                }
            },
            $options = $elem.find("option");
        if (inToolbar) {
            options.minWidth = "auto";
        }
        $grid.triggerHandler("jqGridRefreshFilterValues");
        $elem.multiselect(options);
        $elem.siblings("button.ui-multiselect").css({
            width: "100%",
            margin: "1px 0",
            paddingTop: ".3em",
            paddingBottom: ".3em"
        });
    }, 50);
},
multiselectTemplate = {
    stype: "select", 
    searchoptions: {
        generateValue: true,
        //noFilterText: "Any",
        sopt: ["in"],
        attr: {
            multiple: "multiple",
            size: 4
        },
        dataInit: dataInitMultiselect
    }
};

$("#jqGridA").jqGrid({
    url: "...",
    datatype: "json",
    forceClientSorting: true,
    loadonce: true,
    colNames: ["Client", "Amount", "Tax", "Total", "Shipped via", "Notes"],
    colModel: [
        {name: "name", width: 85, editable: true,
            template: multiselectTemplate},
        {name: "amount", width: 75, template: "number"},
        {name: "tax", width: 52, template: "number"},
        {name: "total", width: 65, template: "number", editable:true},
        {name: "ship_via", width: 85, align: "center",
            template: multiselectTemplate},
        {name: "note", width: 100, sortable: false}
    ],
    rowNum: 10,
    loadui: "block",
    inFilterSeparator: ";",
    multiselect: true,
    multiPageSelection: true,
    loadComplete: function () {
        if (!this.ftoolbar) {
            // create filter toolbar if it isn't exist 
            $(this).jqGrid("filterToolbar", {
                defaultSearch: "cn",
                beforeClear: function() {
                    $(this.grid.hDiv)
                        .find(".ui-search-toolbar button.ui-multiselect")
                        .each(function() {
                        $(this).prev("select[multiple]").multiselect("refresh");
                    });
                }
            });
            $(this).triggerHandler("jqGridRefreshFilterValues");
            $(this.grid.hDiv)
                .find(".ui-search-toolbar button.ui-multiselect")
                .each(function() {
                $(this).prev("select[multiple]")
                    .multiselect("refresh");
            });        
        }
    },
    rowList: [10, 20, 30, 100],
    pager: true,
    pagerRightWidth: 135, // fix wrapping or right part of the pager
    viewrecords: true,
    sortable: true,
    shrinkToFit: false
}).jqGrid("navGrid", {edit: true, add: false, del: false, search: false},
{
  afterComplete: function(response, postdata) {
     $(this).jqGrid('resetSelection');
     var p = $(this).jqGrid("getGridParam");
     p.selarrrow = [];
     beforeProcessingHandler.call(this, p.data);
  }
});