I've looked around, and I can't quite find all the pieces I need to put this together. The problem is that I want to call the same javascript function from multiple places, so I need to pass the element's ID into the function so I can change them all. The idea is very simple. I just want four checkboxes to call this function when clicked so that it will prevent the last box from being unchecked. Here's what I have so far.
HTML:
<asp:CheckBox ID="cbBlue" Text="Blue" Checked="true" runat="server" />
<asp:CheckBox ID="cbGreen" Text="Green" Checked="true" runat="server" />
<asp:CheckBox ID="cbRed" Text="Red" Checked="true" runat="server" />
<asp:CheckBox ID="cbYellow" Text="Yellow" Checked="true" runat="server" />
<asp:HiddenField ID="hdnCheckCount" runat="server" Value="4" />
C#:
protected void Page_Load(object sender, EventArgs e)
{
cbBlue.Attributes.Add("onclick", "checkCheck(" + this.ClientID + ")");
cbGreen.Attributes.Add("onclick", "checkCheck(" + this.ClientID + ")");
cbRed.Attributes.Add("onclick", "checkCheck(" + this.ClientID + ")");
cbYellow.Attributes.Add("onclick", "checkCheck(" + this.ClientID + ")");
}
Javascript:
function checkCheck(elementID) {
if ($('#<%=hdnCheckCount.ClientID%>').val() == 1) {
elementID.prop("checked", true);
return;
}
else {
if (elementID.is(":checked")) {
elementID.prop("checked", false);
$('#<%=hdnCheckCount.ClientID%>').val($('#<%=hdnCheckCount.ClientID%>').val() - 1);
}
else {
elementID.prop("checked", true);
$('#<%=hdnCheckCount.ClientID%>').val($('#<%=hdnCheckCount.ClientID%>').val() + 1);
}
}
}
Is this possible? Am I close? Also, I'm a little unsure about whether I need to actually set the checked state of the boxes in the javascript, since I guess that's already handled elsewhere. But then I'm not sure about whether forcing it to true would work, since it might still be unchecked after the javascript function runs.