How to check all asp.net checkboxes on single asp.net button click event
if i have 45 checkboxes inside panel1 开发者_StackOverflowi want on button click event all the checkboxes will be checked and on another button click event all checkboxes will be unchecked...
how to do it using jquery, javascript or vb.net ?
With jQuery you can do
var $checkboxes = $('input[type=checkbox]');
$('#check').toggle(function() {
$checkboxes.attr('checked', 'checked');
return false;
}, function() {
$checkboxes.removeAttr('checked');
return false;
});
Check working example at http://jsfiddle.net/zgTw3/5/
This is your aspx file code for checkboxes, panel and button;
<asp:Panel ID="Panel1" runat="server">
<asp:CheckBox ID="CheckBox1" runat="server" />
<asp:CheckBox ID="CheckBox2" runat="server" />
<asp:CheckBox ID="CheckBox3" runat="server" />
</asp:Panel>
<asp:Button Text="click" ID="Button1" runat="server" onclick="Button1_Click" />
And this is your c# code for button click event event;
protected void Button1_Click(object sender, EventArgs e) {
foreach (Control c in Panel1.Controls) {
if (c is CheckBox) {
(c as CheckBox).Checked = true;
}
}
}
this is the VB version of this c# code;
Protected Sub Button1_Click(sender As Object, e As EventArgs)
For Each c As Control In Panel1.Controls
If TypeOf c Is CheckBox Then
TryCast(c, CheckBox).Checked = True
End If
Next
End Sub
when you click the button, it should check all the checkboxes in bulk.
EDIT :
if you wanna check the unchecked ones and uncheck the checked ones on the same click, do the following
C# :
protected void Button1_Click(object sender, EventArgs e) {
foreach (Control c in Panel1.Controls) {
if (c is CheckBox) {
if ((c as CheckBox).Checked) {
(c as CheckBox).Checked = false;
} else {
(c as CheckBox).Checked = true;
}
}
}
}
VB :
Protected Sub Button1_Click(sender As Object, e As EventArgs)
For Each c As Control In Panel1.Controls
If TypeOf c Is CheckBox Then
If TryCast(c, CheckBox).Checked Then
TryCast(c, CheckBox).Checked = False
Else
TryCast(c, CheckBox).Checked = True
End If
End If
Next
End Sub
ASP.NET has a bit of a quirk when it comes to rendering ID
s and NAME
s on its controls.
Try something like this instead:
<asp:Button ID="myToggleButton" runat="server" Text="Toggle Checkboxes" />
and then in your script
$('[id$="myToggleButton"]').click(function(){
$('input:checkbox')
.filter(':checked')
.attr('checked',false)
.end()
.not(':checked')
.attr('checked',true)
;
});
or something along the same idea. I'm pretty sure you can optimize that jQuery code a bit more.
精彩评论