javascript 计算gridview中选中的复选框
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/13254388/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Count the checked checkboxes in gridview
提问by Josue P. Corzo
I need to count the checked checkboxes in my gridview, but I don't know how to do it. Maybe I could use JavaScript and save the count in a textbox with style display none. How can I do this?
我需要计算 gridview 中选中的复选框,但我不知道该怎么做。也许我可以使用 JavaScript 并将计数保存在样式显示为 none 的文本框中。我怎样才能做到这一点?
回答by Denys Wessels
I wrote both client and server side ways of doing this, have a look at them and choose the one which suits you best!
我写了客户端和服务器端的方法,看看它们并选择最适合你的方法!
Please note I've used jQueryfor the client side logic as it's the more modern way of manipulating the DOM on the client
请注意,我已经将jQuery用于客户端逻辑,因为它是在客户端上操作 DOM 的更现代的方式
Source:
来源:
%>
%>
<asp:Content ID="HeaderContent" runat="server" ContentPlaceHolderID="HeadContent">
<script src="http://code.jquery.com/jquery-1.8.2.js" type="text/javascript"></script>
<script type="text/javascript">
function GetMarriedEmployees() {
var counter = 0;
$("#<%=gvEmployees.ClientID%> input[id*='chkIsMarried']:checkbox").each(function (index) {
if ($(this).is(':checked'))
counter++;
});
alert(counter);
}
</script>
</asp:Content>
<asp:Content ID="BodyContent" runat="server" ContentPlaceHolderID="MainContent">
<asp:GridView ID="gvEmployees" AutoGenerateColumns="false" runat="server">
<Columns>
<asp:BoundField DataField="EmployeeId" />
<asp:BoundField DataField="EmployeeName" />
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="chkIsMarried" runat="server" Checked='<%# Bind("IsMarried") %>' />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
<asp:Button ID="btnGetMarried" runat="server" Text="Server" OnClick="btnGetMarried_Click" /><br />
<input type="button" value="Client" onclick="GetMarriedEmployees()" />
</asp:Content>
Code behind:
后面的代码:
namespace WebApplication1
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!Page.IsPostBack)
{
List<Employees> employees = new List<Employees>()
{
new Employees{EmployeeId=1, EmployeeName="Bob", IsMarried=true},
new Employees{EmployeeId=2, EmployeeName="John", IsMarried=true}
};
gvEmployees.DataSource = employees;
gvEmployees.DataBind();
}
}
protected void btnGetMarried_Click(object sender, EventArgs e)
{
int marriedEmployees = 0;
foreach (GridViewRow row in gvEmployees.Rows)
{
var isMarried = (CheckBox)row.FindControl("chkIsMarried");
if(isMarried.Checked)
marriedEmployees++;
}
Response.Write(String.Format("Number of married employees = {0}",marriedEmployees.ToString()));
}
public class Employees
{
public int EmployeeId { get; set; }
public string EmployeeName { get; set; }
public bool IsMarried { get; set; }
}
}
EDIT:
编辑:
I suspect that you may be a VB.NET developer so here is the VB version of the server side code:
我怀疑您可能是 VB.NET 开发人员,所以这里是服务器端代码的 VB 版本:
Public Class _Default
Inherits System.Web.UI.Page
Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load
If Not Page.IsPostBack Then
Dim employees As New List(Of Employees)
Dim employee1 As Employees = New Employees()
employee1.EmployeeId = 1
employee1.EmployeeName = "Bob"
employee1.IsMarried = False
Dim employee2 As Employees = New Employees()
employee2.EmployeeId = 2
employee2.EmployeeName = "John"
employee2.IsMarried = True
employees.Add(employee1)
employees.Add(employee2)
gvEmployees.DataSource = employees
gvEmployees.DataBind()
End If
End Sub
Protected Sub btnGetMarried_Click(ByVal sender As Object, ByVal e As EventArgs) Handles btnGetMarried.Click
Dim marriedEmployees As Integer = 0
For Each row As GridViewRow In gvEmployees.Rows
Dim isMarried As CheckBox = row.FindControl("chkIsMarried")
If isMarried.Checked Then
marriedEmployees += 1
End If
Next
Response.Write(String.Format("Number of married employees = {0}", marriedEmployees))
End Sub
End Class
Public Class Employees
Public Property EmployeeId As Integer
Public Property EmployeeName As String
Public Property IsMarried As Boolean
End Class
回答by chridam
A javascript solution:
一个javascript解决方案:
function CheckBoxCount() {
var gv = document.getElementById("<%= Gridview1.ClientID %>");
var inputList = gv.getElementsByTagName("input");
var numChecked = 0;
for (var i = 0; i < inputList.length; i++) {
if (inputList[i].type == "checkbox" && inputList[i].checked) {
numChecked = numChecked + 1;
}
}
alert(numChecked);
}
Markup:
标记:
<asp:GridView AllowSorting="true" ID="Gridview1" Width="98%" AutoGenerateColumns="False" runat="server">
<Columns>
<asp:TemplateField>
<ItemTemplate>
<asp:CheckBox ID="cb_count" runat="server" onclick="CheckBoxCount();"></asp:CheckBox>
</ItemTemplate>
</asp:TemplateField>
...
</Columns>
</asp:GridView>
回答by Ahmad
Dim cnt as Integer = 0
For i=0 to GridView1.Rows.Count -1
Dim chk as CheckBox = TryCast( GridView1.Row(i).Controls.Find("nameOfCheckBoxControlColum"),CheckBox)
if chk.Checked=True Then cnt += 1
Next
'Now cnt holds the number of Checked Boxes.
回答by Baya
var count = $('input[name="numbChecked"]:checked').length;
it's the easiest way to get the count without any trouble and extra explanation! :)
这是获得计数的最简单方法,没有任何麻烦和额外解释!:)
回答by Hafsal
This will help you
这会帮助你
function Calculation()
{
var grid = document.getElementById("<%=grdSelectFees.ClientID%>"); //grdSelectFees GridViewId
for (var i = 0; i < grid.rows.length - 1 ; i++)
{
var CheckBox1 = $("input[id*=chkRow]")//chkRow Id of Check box
if (CheckBox1[i].type == "checkbox" && CheckBox1[i].checked)
{
//Code For If check Box Is Checked
}
}
}