【问题标题】:free-jqgrid: mutliselect in free-jqgrid 4.14.0free-jqgrid:free-jqgrid 4.14.0 中的多选
【发布时间】:2017-03-08 02:54:48
【问题描述】:

不确定为什么当我选择多个值时多选不起作用。我正在使用来自 erichynds 的 free-jqgrid 4.14.0 和多选 js。 多选也不是下拉菜单。我是否缺少任何 CSS 或任何东西...

请帮忙...

创建了小提琴,但由于我无法在工作场所使用小提琴,所以我使用了手机,所以它现在无法使用。我肯定错过了什么。 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>

【问题讨论】:

    标签: jquery jqgrid free-jqgrid


    【解决方案1】:

    您使用了非常古老的代码示例,这是我在开始免费 jqGrid 项目之前编写的。免费的 jqGrid 现在支持许多功能,可以简化代码(并使其工作)

    演示https://jsfiddle.net/OlegKi/h0mwtw8s/使用如下代码:

    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);
      }
    });
    

    【讨论】:

    • 我们不能像之前那样设置多选下拉列表的值吗?例如,我的多选下拉值来自另一个服务。较早的方法是:searchoptions: { sopt: ['eq','ne'], value: scorecardAsString, attr: {multiple: 'multiple', size: 3}, dataInit: dataInitMultiselect }
    • 感谢 Oleg,我发现从旧版本的 JQGrid 迁移到最新版本并不容易。进行此更改后,我现在面临很多问题。
    • @SKumar:抱歉,您使用的是 4.3 版本,它已经超过 5 年了。您必须迁移到多年前的更新版本。你现在必须做的工作,你去年跳过。我建议你在发布下一个版本后直接迁移到新版本(或测试一些兼容性问题)。例如,Chrome 和 Firefox 都只支持最新和以前的版本。 Chrome 每 1.5 个月发布一次新版本。因此,您必须在 1-3 个月内组织迁移到 Chrome 的下一个版本。 5 年的 web 开发是不可接受的。
    • 我已经升级到 4.13。现在,在我进行此更改后,冻结的列无法正常工作。冻结的标题正在工作,但身体却没有。即使升级到 4.14 后,冻结的列也可以正常工作。但是当我更改代码使多选工作时,那个时候,所有问题都来了......
    • @SKumar:4.13 版比一年前发布得更多。之后我从 4.13.1 到 4.13.6 发布了 6 下一个版本。免费 jqGrid 长期以来一直支持“in”操作(参见 4.13.3 和 4.13.4 版本之间发布的the issue)。我不确定你现在的问题是什么。我不能为你迁移你的程序。
    猜你喜欢
    • 1970-01-01
    • 2023-04-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-24
    • 1970-01-01
    相关资源
    最近更新 更多