I was given the code below to disable a button on an ASP.Net page if none of the checkboxes are checked, and to enable it if any checkboxes get checked. It disables the button fine when the page loads and no boxes are checked, but never hits the $(‘.cb’).change(setButton) code to enable the button when I check one of the checkboxes. Anyone know what might be wrong?
<!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>
</head>
<body>
<form id="form1" runat="server">
<div>
<asp:CheckBox ID="CheckBox1" runat="server" CssClass="cb" />
<asp:CheckBox ID="CheckBox2" runat="server" CssClass="cb" />
<asp:Button ID="Button1" runat="server" CssClass="button"
Text="Button" />
</div>
</form>
<script language="jquery" src="js/jquery-1.3.2.js" type="text/javascript">
</script>
<script type="text/javascript" >
$(document).ready(function() {
function setButton() {
$('#Button1').attr('disabled', $('.cb:checked').length === 0);
}
// run check after changing any of the checkboxes
$('.cb').change(setButton);
// initial check
setButton();
});
</script>
Your problem is that you’re attaching a handler to the
changeevent instead of theclickevent.There’s another problem wherein asp.net doesn’t put the
CssClassof your<asp:CheckBox>on the rendered<input>element, but instead on a containing<span>element. That behavior might be specific to the .net framework version which I use but you might inspect your rendered HTML to verify that your jQuery selectors are accurate.