是否有直接的方法在jqGrid中选择组内的行?

时间:2010-12-09 19:24:07

标签: jquery jquery-selectors jqgrid checkbox grouping

我正在使用基于州或省分组的jqGrid。组内的每一行都有一个复选框。我需要在组头中放置一个复选框,允许用户选择/取消选择该组中的所有行复选框。

在查看jqGrid生成的HTML时,我没有看到任何与组内行相关的类或ID。我也没有看到使用列选项或分组配置添加此类的方法。

有什么建议吗?

2 个答案:

答案 0 :(得分:1)

我们已经用子网格解决了同样的问题,解决方案可能适用于分组方案。我们使用custom formatters为标题链接/复选框和子网格复选框添加样式和数据属性。然后我们在标题行中有一个链接或复选框,其上有一个事件,它使用jQuery选择子网格中具有相应数据属性和样式的所有复选框。最后,grid load complete事件为“check all”链接添加了click事件处理程序。

这是subgrid复选框列的示例自定义格式化程序。请注意data-groupingId属性,该属性存储用于将标题行与子网格行相关联的值。

function checkBoxColumnFormatter(cellvalue, options, rowObject) {
    return "<input type=\"checkbox\"" + data-groupingId=\"" + rowObject.GroupingId + "\" class=\"subgridCheck\" />";
}

以下是“全部检查”列的示例自定义格式化程序。请注意data-groupingId属性,该属性存储用于将标题行与子网格行相关联的值。

function checkAllColumnFormatter(cellValue, options, rowObject) {
    var link = $("<a class=\"checkAll\" href=\"#\" data-groupingId=\"" + rowObject.Id + "\">Check All</a>");

    var linkHtml = $("<div>").append(link.clone()).remove().html();

    return linkHtml;
}

这是加载完成事件,它挂接了上述格式化程序中创建的“全部检查”链接的点击事件。

function mainGridLoadComplete(data) {
    $(".checkAll").click(function (e) {
        checkSubGridRows(
            $(this).attr("data-groupingId")); // Use the data attribute to specify the value that will be on all the *relevant* subgrid checkboxes.
    });
},

最后,这是完成工作的方法。

function checkSubGridRows(groupingId) {
    $("#GridId .subgridCheck[data-groupingId=\"" + groupingId + "\"]").not(":disabled").each(
        function () {
            $(this).attr("checked", "checked");
        });
}

这对我们来说非常有效。考虑到所有事情,当事情变得如此复杂时,我宁愿有一个客户端模型来接收来自JSON Web服务的数据,并成为jqGrid的权威来源。我认为这最终会让jqGrid抓取数据本身并吞下实际的数据对象,这使得很难或不可能直接获取数据以供参考或处理。但是,创建和管理客户端模型/视图分离并非易事。所以这可以作为一种快速替代方案。但要注意,因为这可能会变得无法控制。

答案 1 :(得分:1)

我们在不使用子网格的情况下解决了这个问题。 请检查以下内容是否符合您的要求。

HTML代码从这里开始

<%@ Page Language="C#" AutoEventWireup="true" CodeBehind="Default.aspx.cs" Inherits="Jquery3._Default" %>

<%@ Register Assembly="Trirand.Web" TagPrefix="trirand" Namespace="Trirand.Web.UI.WebControls" %>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <link rel="stylesheet" type="text/css" media="screen" href="http://ajax.aspnetcdn.com/ajax/jquery.ui/1.8.11/themes/redmond/jquery-ui.css" />

    <script src="js/jquery-1.5.2.min.js" type="text/javascript"></script>

    <link rel="stylesheet" type="text/css" media="screen" href="themes/ui.jqgrid.css" />

    <script src="js/trirand/i18n/grid.locale-en.js" type="text/javascript"></script>

    <script src="js/trirand/jquery.jqGrid.min.js" type="text/javascript"></script>
<%--Html Code begins here --%>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <script type="text/javascript">
            /**
            * Format the column [AsOfDate].
            * Places label for the columns in the grouped rows
            * places Checkbox in the Group header
            */
            function formatAsOfDate(cellvalue, options, rowObject)
            {
                if (parseInt(options.rowId) > 0)
                {

                    return "<label>" + cellvalue + "<label/>";
                }
                else
                {
                    return "<input type=checkbox value=" + cellvalue + " onclick='SelectCheckbox(this," + options.rowId + ")'/>" + cellvalue;
                }

            }

            /**
            * Format the column [DebtStatusId].
            * Places label for the columns in the grouped rows
            * places Checkbox in the Group header
            */
            function formatDebtStatusId(cellvalue, options, rowObject)
            {
                if (parseInt(options.rowId) > 0)
                {

                    return "<label>" + cellvalue + "<label/>";
                }
                else
                {
                    return "<input type=checkbox value=" + cellvalue + " onclick='SelectCheckbox(this," + options.rowId + ")'  />" + cellvalue;
                }

            }

            /**
            * To select/Deselect all the grouped rows based on the checkbox selected at group level.
            */
            function SelectCheckbox(chkbox, groupingId)
            {

                var grid = jQuery("#<%= JQGrid1.ClientID %>");

                var Rows = grid.find("TR");
                $.each(Rows, function(i, item)
                {
                    var label = $(item).find("label");
                    if (label.length > 0)
                    {
                        $.each(label, function(i, labelitem)
                        {
                            if (labelitem.innerText === chkbox.defaultValue)
                            {
                                var CheckBox = $(item).find("INPUT.cbox");
                                $(chkbox).click(function()
                                {
                                    if ($(this).attr("checked"))
                                    {
                                        CheckBox.attr("checked", "checked");
                                    }
                                    else
                                    {
                                        CheckBox.removeAttr("checked");
                                    }
                                })
                            }
                        })

                    }
                });
            }

            /**
            * To Edit the Selected Row(s).
            */
            function Selectedrow()
            {
                var grid = jQuery("#<%= JQGrid1.ClientID %>");
                var rowKey = grid.getGridParam("selarrrow");
                if (rowKey)
                {
                    grid.editGridRow(rowKey, grid.editDialogOptions, { reloadAfterSubmit: false });
                }
                else
                {
                    alert("No rows are selected");
                }

            }


        </script>

        <span style="font-size: 140%"><b>Group grid by:</b> </span>
        <asp:DropDownList runat="server" ID="groupColumnDdl" AutoPostBack="true">
            <asp:ListItem Text="DebtStatusID" Value="DebtStatusID" />
            <asp:ListItem Text="AsOfDate" Value="AsOfDate"></asp:ListItem>
        </asp:DropDownList>
        <trirand:JQGrid ID="JQGrid1" runat="server" Height="200px" OnRowEditing="JQGrid1_RowEditing"
            AppearanceSettings-Caption="First Grid"  MultiSelect="true">
            <Columns>
                <trirand:JQGridColumn DataField="DebtID" PrimaryKey="True" />
                <trirand:JQGridColumn DataField="SequenceNumber" Editable="true" />
                <trirand:JQGridColumn DataField="DebtStatusID">
                 <Formatter>
                        <trirand:CustomFormatter FormatFunction="formatDebtStatusId" />
                    </Formatter>
                </trirand:JQGridColumn>
                <trirand:JQGridColumn DataField="AsOfDate" DataFormatString="{0:d}">
                    <Formatter>
                        <trirand:CustomFormatter FormatFunction="formatAsOfDate" />
                    </Formatter>
                </trirand:JQGridColumn>
                <trirand:JQGridColumn DataField="Alias" Editable="true" />                
            </Columns>
            <SortSettings InitialSortColumn="DebtID"></SortSettings>
            <EditDialogSettings CloseAfterEditing="false" />
            <AppearanceSettings ShowRowNumbers="True" Caption="First Grid"></AppearanceSettings>
            <ToolBarSettings ShowEditButton="true" ShowRefreshButton="True" />
        </trirand:JQGrid>
        <input type="button" onclick="Selectedrow()" value="Edit" />
        <div style="display: none;">
            <input type='checkbox' id="chkTest" runat="server" />
        </div>
    </div>
    </form>
</body>
</html>

Cs Code在这里开始

    using System;
using System.Collections;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using System.Data;
using System.Data.SqlClient;
using Trirand.Web.UI.WebControls;

namespace Jquery3
{
    public partial class _Default : System.Web.UI.Page
    {
        protected void Page_Load(object sender, EventArgs e)
        {

            JQGrid1.DataSource = GetData();
            JQGrid1.DataBind();

            GroupField gf = new GroupField();
            //Dynamic Grouping based on the combo value selected
            switch (groupColumnDdl.SelectedValue)
            {
                case "DebtStatusID":
                    gf = new GroupField { DataField = "DebtStatusID", HeaderText = "DebtStatus ID : {0}", GroupSortDirection = Trirand.Web.UI.WebControls.SortDirection.Asc, ShowGroupColumn = true, ShowGroupSummary = false };
                    break;
                case "AsOfDate":
                    gf = new GroupField
                    {
                        DataField = "AsOfDate",
                        HeaderText = "AsOfDate : {0}",

                        GroupSortDirection = Trirand.Web.UI.WebControls.SortDirection.Asc,
                        ShowGroupColumn = true,
                        ShowGroupSummary = false
                    };
                    break;
            }
            JQGrid1.GroupSettings.GroupFields.Add(gf);
        }

        protected void JQGrid1_RowEditing(object sender, Trirand.Web.UI.WebControls.JQGridRowEditEventArgs e)
        {

            var rows = e.RowKey;
            ArrayList ArrayOfIds = new ArrayList(rows.Split(new char[] { ',' }));
            for (int i = 0; i < ArrayOfIds.Count; i++)
            {
                DataSet ds = GetData();
                DataTable dt = ds.Tables[0];
                dt.PrimaryKey = new DataColumn[] { dt.Columns["DebtID"] };
                DataRow rowEdited = dt.Rows.Find(ArrayOfIds[i]);
                rowEdited["SequenceNumber"] = e.RowData["SequenceNumber"];
                rowEdited["DebtStatusID"] = e.RowData["DebtStatusID"];
                rowEdited["Alias"] = e.RowData["Alias"];
            }
            JQGrid1.DataSource = GetData();
            JQGrid1.DataBind();
        }

        protected DataSet GetData()
        {
            if (Session["EditDialogData"] == null)
            {
                string ConnectionString = "Data Source =192.168.0.20; Initial Catalog = LW_TTX_IMPL; User ID=Development;password=jk;";
                DataSet ds = new DataSet();
                SqlConnection sqlconn = new SqlConnection(ConnectionString);
                SqlDataAdapter sqlAdp = new SqlDataAdapter();
                sqlAdp.SelectCommand = new SqlCommand("SELECT DebtID,SequenceNumber,DebtStatusID,AsOfDate,'Alias'+Alias Alias FROM Debt_Profile", sqlconn);
                sqlAdp.Fill(ds);
                Session["EditDialogData"] = ds;
                return ds;
            }
            else
            {
                return Session["EditDialogData"] as DataSet;
            }
        }
    }
}