通过选择另一个复选框来选择所有复选框
问题描述:
Hello guys我开始使用jquery,当我尝试通过单击另一个复选框来选择页面中的所有复选框时遇到问题。通过选择另一个复选框来选择所有复选框
这是我的jQuery代码:
$('.selecionarTodos').live('click', function() {
alert("test");
var checkbox = $(this).children('td').children('[type="checkbox"]');
$('.headerChkItem').each(function() {
if (checkbox.is(':checked')) {
$(this).css('background-color', '');
checkbox.attr('checked', false);
$(this).children('td').children('[id*="hfSelecionada"]').val('false');
qtdTotal = qtdTotal - parseFloat($(this).children('.quantidade').text().replace(',', '.'));
}
else {
$(this).css('background-color', '#e8f783');
checkbox.attr('checked', true);
$(this).children('td').children('[id*="hfSelecionada"]').val('true');
qtdTotal = qtdTotal + parseFloat($(this).children('.quantidade').text().replace(',', '.'));
}
});
});
,这是我的客户端代码:
<asp:TemplateField HeaderText="Selecionar" ItemStyle-HorizontalAlign="Center">
<HeaderTemplate>
<input type="checkbox" id="headerChkItem" cssclass="selecionarTodos" runat="server" />
</HeaderTemplate>
<ItemTemplate>
<input type="checkbox" id="chkItem" disabled="disabled" cssclass="selecionado" runat="server" />
</ItemTemplate>
</asp:TemplateField>
PS:当我测试jQuery的 “警报” 没有运行。 在此先感谢。
答
您需要将其从id="headerChkItem"
更改为class="headerChkItem"
另外 - 是"cssclass"
服务器端语言的一部分吗?或者应该是"class"
?
答
我猜测您的服务器代码(从你的例子)看起来是这样的:
<asp:ObjectDataSource runat="server" ID="DataSource" SelectMethod="GetData" TypeName="WebApplication1.Test"></asp:ObjectDataSource>
<asp:GridView runat="server" ID="Grid" DataSourceID="DataSource">
<Columns>
<asp:TemplateField HeaderText="Selecionar" ItemStyle-HorizontalAlign="Center">
<HeaderTemplate>
<input type="checkbox" class="selecionarTodos headerChkItem" runat="server" />
</HeaderTemplate>
<ItemTemplate>
<input type="checkbox" disabled="disabled" class="selecionado chkItem" runat="server" />
</ItemTemplate>
</asp:TemplateField>
</Columns>
</asp:GridView>
,为此格,你需要这样的:主要是
$('.selecionarTodos').on('click', function() {
var gridCheckboxes = $(this).parents('table').find('input:checkbox.chkItem');
var qtdTotal = 0;
if ($(this).is(':checked')) {
$(this).css('background-color', '');
gridCheckboxes.attr('checked', true);
qtdTotal = qtdTotal - parseFloat($(this).children('.quantidade').text().replace(',', '.'));
} else {
$(this).css('background-color', '#e8f783');
gridCheckboxes.attr('checked', false);
qtdTotal = qtdTotal + parseFloat($(this).children('.quantidade').text().replace(',', '.'));
}
});
你的错误:
- 使用cssclass属性时类是正确的
- 错误地选择了表格中的复选框
我还是不明白你为什么使用每个循环的所有标题复选框。我发布的代码只是位于标题复选框,当您单击它时,将根据标题复选框状态选中或取消选中网格中的所有其他复选框。
好的,我已经改变了cssclass,并且它已经被执行了,但是现在我仍然必须通过点击这个复选框来选择所有的itens,我必须循环所有的网格线吗? – guisantogui 2013-04-22 15:06:52
你可以在客户端发布HTML,而不是上面的服务器端代码吗?我看不到标签在哪里,等等。另外 - 你是否将ID改为一个类? – 2013-04-22 15:13:20