在回发问题上使用javascript在gridview中选择

SelectAll in gridview using javascript on postback issue

本文关键字:javascript gridview 选择 问题      更新时间:2023-09-26

我有一个gridview,其中有一个复选框列。此列的标题是一个复选框。

当选中时,所有的值都被选中,反之亦然。

我使用javascript。

问题是,如果我检查它并在需要回发的页面上执行任何其他事件,则检查值消失。我不想让他们消失。

下面是我的代码:
 <script  type="text/javascript">
 function checkAllBoxes() {
      //get total number of rows in the gridview and do whatever
      //you want with it..just grabbing it just cause
      var totalChkBoxes = parseInt('<%= GridView1.Rows.Count %>');
      var gvControl = document.getElementById('<%= GridView1.ClientID %>');
      //this is the checkbox in the item template...this has to be the same name as the ID of it
      var gvChkBoxControl = "Select_CheckBox";
      //this is the checkbox in the header template
      var mainChkBox = document.getElementById("chkBoxAll");
      //get an array of input types in the gridview
      var inputTypes = gvControl.getElementsByTagName("input");
      for (var i = 0; i < inputTypes.length; i++) {
          //if the input type is a checkbox and the id of it is what we set above
          //then check or uncheck according to the main checkbox in the header template             
          if (inputTypes[i].type == 'checkbox' && inputTypes[i].id.indexOf(gvChkBoxControl, 0) >= 0)
              inputTypes[i].checked = mainChkBox.checked;
      }
  }
  </script>
<asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="false">
<Columns>
<asp:TemplateField>
   <HeaderTemplate>
     <input id="chkBoxAll" type="checkbox" onclick="checkAllBoxes()"/>
   </HeaderTemplate>
   <ItemTemplate>
     <asp:CheckBox ID="Select_CheckBox" runat="server" />
   </ItemTemplate>
</asp:TemplateField>
 <!-- The rest of your rows here -->
</Columns>
</asp:GridView>

谢谢你的帮助

通过添加runat="server"使您的复选框成为使用视图状态的服务器端控件。然后,它将在多次回发中保持其值。

<input id="chkBoxAll" type="checkbox" onclick="checkAllBoxes()" runat="server"/>

并更改JavaScript以选择以chkBoxAll结尾的id。我在下面的例子中使用jQuery:

//this is the checkbox in the header template
var mainChkBox = $('input[id$="chkBoxAll"]');

但是,如果您对gridview行进行排序或使用分页,您可能会遇到不太友好的行为。