Allow [any one] OR [two specific] checkboxes to be checked on ASP.Net Web Form.

Hi Experts,

I have an ASP.Net web form with about a dozen CheckBox's like so:

1st <asp:CheckBox ID="VeteranServ".../>
2nd <asp:CheckBox ID="ResourceRoom".../>
3rd <asp:CheckBox ID="Unemployment".../>
4th <asp:CheckBox ID="JobClub".../>
5th <asp:CheckBox ID="Workshop".../>

I want to treat them like RadioButtons where only one may be selected at a time, with the exception of the 2nd and 3rd.  The 2nd one may be selected alone or WITH the 3rd but the 3rd REQUIRES that the 2nd also be selected.  I'm currently accomplishing that functionality like so:

<asp:CheckBox ID="ResourceRoom" runat="server" Text="Resource Room Services" name="Services" ValidationGroup="ResourceRoom"
	onclick="if(!this.checked){document.getElementById('Unemployment').checked=this.checked}" />&nbsp; 
<span class="style4">(To use computers for job searching, filing for Unemployment, etc.)</span>
<br />
<asp:CheckBox ID="Unemployment" type="checkbox" name="Services" runat="server" Text="File for Unemployment Benefits"
	onclick="document.getElementById('ResourceRoom').checked=this.checked" ValidationGroup="ResourceRoom" />&nbsp;
<span class="style4">(Requires Resource Room Services)</span>

Open in new window


That works just fine, but the rest of the CheckBoxes can be selected at the same time and I don't want that.  I want RadioButton functionality on them all and also the existing functionality where #2 and #3 may both be selected, #2 may be selected either alone or with #3, but if #3 is selected it requires that #2 is selected.

To limit the number of CheckBoxes checked I'm currently using this after the submit button is clicked, but this is a crappy way to do it and does not provide immediate feedback like a RadioButton function would:
    <script type="text/javascript">
        function check() {
                var Inputs;
                Inputs = document.getElementsByTagName("input");
            var checkCount = 0;
            for (var n = 0; n < Inputs.length; ++n) {
                if (Inputs[n].type == 'checkbox' && Inputs[n].checked) {
                    checkCount++;
                }
            }
            if (checkCount < 1) {
                alert("Please select the Service you will be using today.");
                return false;
            }
            if (checkCount > 2) {
                alert("Please select only one service at this time." + "\n \n" + "( Resource Room plus \n File for Unemployment Benefits \n counts as only one. )");
                return false;
            }
            return true;
        }
    </script>

Open in new window

Thank you in advance!
David
LVL 1
megninAsked:
Who is Participating?

Improve company productivity with a Business Account.Sign Up

x
 
megninConnect With a Mentor Author Commented:
I give up.
0
 
RouchieCommented:
Why not use RadioButtons instead, but have checkboxes for the 'nested' selection?  I would then use JQuery to show/hide the checkboxes completely based on the chosen radio button value.  Put the checkboxes in a parent div container then show/hide that based on the radio button selection -> http://www.mkyong.com/jquery/how-to-select-a-radio-button-with-jquery/
0
 
megninAuthor Commented:
Because I have other "child" functionality on some of the CheckBoxes that I did not include in the question because it wasn't relevant.  
I asked the question the way I need the solution, but thanks for reading my question anyway. ;-)
0
Get your problem seen by more experts

Be seen. Boost your question’s priority for more expert views and faster solutions

 
RouchieCommented:
I thought you might...!  

The reason I posted the proposal anyway is that based on this statement, ' I want RadioButton functionality on them all' , I think you need to re-think your strategy both for a programming advantage and a user interface improvement.

It's extremely easy in JQuery to reset things based on form choices, so you might as well start with the UI functionality radio buttons provide to begin with, then build upon that, rather than re-invent stuff.
0
 
RouchieCommented:
If you're using ASP.NET, then perhaps put everything inside an UpdatePanel, and postback on each radio button press, showing only the correct parts of the UI for each choice made?
0
 
megninAuthor Commented:
Well, the original design called for a dozen CheckBoxes were "Select all that apply" applied.
Then, sub-selections were added were added to one of the CheckBoxes so that IF you checked "See a Counselor" THEN you have to select from one of the nine RadioButtons to select the particular Program you are seeing a Counselor about.
Then the design specs changed so that only one item could be selected.  Then so that two particular items could be selected.
If you want to rewrite the entire form for my you are entirely welcome to do so.  Otherwise all I need is a little JavaScript to function as I stated in the question.
I appreciate your input and I will consider your advice in the future, but you posted your proposal based on only half of my statement, where the second half which you did not consider was the overriding consideration.
0
 
megninAuthor Commented:
I've requested that this question be deleted for the following reason:

One expert took the question down a rabbit hole of asking me why I didn't design the project differently from the beginning instead of providing any suggestions related to my question. &nbsp;I need a fairly simple JavaScript solution not suggestions that the project should have had a different design from the beginning. &nbsp;I have no control over the &quot;feature creep&quot; that happened between the initial design specifications and what it has evolved into. &nbsp;I just need to add functionality that is requested. &nbsp;I wish to re-submit the question without the non-relevant inputs from the one expert who responded with repeated unhelpful suggestions.
0
 
ProculopsisCommented:
<!-- here's the first bit -->

<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <title> - jsFiddle demo</title>
 
  <script type='text/javascript' src='http://code.jquery.com/jquery-1.7.1.js'></script>
 
<script type='text/javascript'>//<![CDATA[
$(function(){
$(".radio").click(function() {
    if ($(this).is(":checked")) {
        $(this).siblings().each(function() {
            this.checked = false;
        });

    }
});
});//]]>  

</script>

</head>
<body>
  1st <input type=CheckBox ID="VeteranServ" class="radio" /> <br />
2nd <input type=checkBox ID="ResourceRoom" class="radio" /> <br />
3rd <input type=checkBox ID="Unemployment" class="radio" /> <br />
4th <input type=checkBox ID="JobClub" class="radio" /> <br />
5th <input type=checkBox ID="Workshop" class="radio" /> <br />
 
</body>
</html>
0
 
RouchieCommented:
That comment is an absolute disgrace.  

If you had posted your full reasoning from the beginning then I wouldn't have wasted my time or yours.   It is my UNPAID job to ensure that you not only get a solution, but one that works well into the future, that you don't need to keep redesigning time and time again.  By thinking proactively you can avoid all this wasted time.
0
 
megninAuthor Commented:
Proculopsis,

Yes, that partly what I need.  Now it needs to allow #2 and #3 to both be checked, but #3 can not be checked alone.  If #3 is checked, then #2 must always also be checked.

The below accomplishes that part of it, so if this functionality was added to your suggestion, that's what I need.
<asp:CheckBox ID="ResourceRoom" runat="server" Text="Resource Room Services" name="Services" ValidationGroup="ResourceRoom"
	onclick="if(!this.checked){document.getElementById('Unemployment').checked=this.checked}" />&nbsp; 
<span class="style4">(To use computers for job searching, filing for Unemployment, etc.)</span>
<br />
<asp:CheckBox ID="Unemployment" type="checkbox" name="Services" runat="server" Text="File for Unemployment Benefits"
	onclick="document.getElementById('ResourceRoom').checked=this.checked" ValidationGroup="ResourceRoom" />&nbsp;
<span class="style4">(Requires Resource Room Services)</span>

Open in new window

0
 
ProculopsisCommented:
<!-- try this -->

<!DOCTYPE html>
<html>
<head>
  <meta http-equiv="content-type" content="text/html; charset=UTF-8">
  <title> - jsFiddle demo</title>
 
  <script type='text/javascript' src='http://code.jquery.com/jquery-1.7.1.js'></script>
 
<script type='text/javascript'>//<![CDATA[
$(function(){
$(".radio").click(function() {
    if ($(this).is(":checked")) {
        if ($(this).is($(".radio").eq(2))) {
            $(this).siblings().each(function() {
                this.checked = false;
            });
            $(".radio").eq(1).prop({
                checked: true
            });
        } else if ($(this).is($(".radio").eq(1))) {
            if (!$(".radio").eq(2).is(":checked")) {
                $(this).siblings().each(function() {
                    this.checked = false;
                });
            }
        } else {
            $(this).siblings().each(function() {
                this.checked = false;
            });
        }
    }
});
});//]]>  

</script>

</head>
<body>
  1st <input type=CheckBox ID="VeteranServ" class="radio" /> <br />
2nd <input type=checkBox ID="ResourceRoom" class="radio" /> <br />
3rd <input type=checkBox ID="Unemployment" class="radio" /> <br />
4th <input type=checkBox ID="JobClub" class="radio" /> <br />
5th <input type=checkBox ID="Workshop" class="radio" /> <br />        
 
</body>
</html>
0
 
megninAuthor Commented:
Yes, when #3 is selected #2 is also selected.  That is good.
Only one more thing, when #2 is unselected then #3 shoud also be unselected because #3 can not be selected alone.

Almost there.  :-)
0
 
megninAuthor Commented:
Also, please tell me what I would need to modify if CheckBox #2 is actually the third or fourth CheckBox on the form.  I can almost pick apart regular JavaScript and modify it to my needs, but jQuery is total Greek to me.  What is .eq(2) and .eq(1).prop ?  Thanks for the mini-tutorial.  ;-)
0
 
megninAuthor Commented:
If #2 is unchecked #3 is not being unchecked.  When both are checked and #2 is unchecked, #3 is being left checked.  #3 can not be checked alone.  Thanks.
0
 
megninAuthor Commented:
Since I'm using ASP.Net when I put Class="radio" in the CheckBox it is actually rendered as:

<span class="radio" name="Services"><input id="VeteranServ" type="checkbox" name="VeteranServ" /><label for="VeteranServ">Veteran Services</label></span>

The class is put on the Span in the Source View.  How do I make it work with ASP.Net CheckBoxes?
0
 
megninAuthor Commented:
I added this in the code behind and moved the function to the bottom of the file and it still doesn't do anything in the .aspx file.  It worked in the jsFiddle page but not the .aspx page.  Except that the third check box does check the second one, but they do not function like radiobuttons.  I can check every one of the boxes.

    Protected Sub Page_Load(sender As Object, e As System.EventArgs) Handles Me.Load
        VeteranServ.InputAttributes.Add("class", "radio")
        DisabilityServ.InputAttributes.Add("class", "radio")
        ResourceRoom.InputAttributes.Add("class", "radio")
        Unemployment.InputAttributes.Add("class", "radio")
        JobClub.InputAttributes.Add("class", "radio")
        Workshop.InputAttributes.Add("class", "radio")
        BondingProgram.InputAttributes.Add("class", "radio")
        Training.InputAttributes.Add("class", "radio")
        GeneralInfo.InputAttributes.Add("class", "radio")
        Interview.InputAttributes.Add("class", "radio")
        SeeSuccessCoach.InputAttributes.Add("class", "radio")

Open in new window


...
<head runat="server">
    <title>Sign In Test</title>
	<script src="Scripts/jquery-1.7.2.min.js" type="text/javascript"></script>
...
            <tr>
                <td colspan="6">
                    <asp:CheckBox ID="VeteranServ" runat="server" Text="Veteran Services" name="Services" />
                    <div id="toggle"></div>
                    <asp:CheckBox ID="DisabilityServ" type="checkbox" name="Services" runat="server"
                                  Text="Services for People with Disabilities" ValidationGroup="ResourceRoom" />
                        <br />
                    <asp:CheckBox ID="ResourceRoom" runat="server" Text="Resource Room Services" name="Services" ValidationGroup="ResourceRoom"
                    	onclick="if(!this.checked){document.getElementById('Unemployment').checked=this.checked}" />&nbsp; 
                    <span class="style4">(To use computers for job searching, filing for Unemployment, etc.)</span>
                    <br />
                    <asp:CheckBox ID="Unemployment" type="checkbox" name="Services" runat="server" Text="File for Unemployment Benefits"
                        onclick="document.getElementById('ResourceRoom').checked=this.checked" ValidationGroup="ResourceRoom" />&nbsp;
                    <span class="style4">(Requires Resource Room Services)</span>
                        <br />
                    <asp:CheckBox ID="JobClub" type="checkbox" name="Services" runat="server" Text="Job Club" ValidationGroup="ResourceRoom" />&nbsp;<span
                        class="style4">(WTP Employment Assistance Program)</span>
                        <br />
                    <asp:CheckBox ID="Workshop" runat="server" name="Services" Text="Attend or sign up for a Workshop" />&nbsp;
                    <span class="style4">(The Workshop Schedule is posted by the door.)</span><br />
                    <asp:CheckBox ID="BondingProgram" type="checkbox" name="Services" runat="server"
                        Text="Federal Bonding Program" ValidationGroup="ResourceRoom" />&nbsp;
                    <span class="style4">(For ex-offenders and persons with a poor credit history)</span>
                        <br />
                    <asp:CheckBox ID="Training" runat="server" name="Services" Text="Receive up to $6,000 to train for a new career." />&nbsp;
                    <span class="style4">(Restrictions apply.)</span>
                        <br />
                    <asp:CheckBox ID="GeneralInfo" runat="server" name="Services" Text="General Information" />&nbsp;
                    <span class="style4">(The person at the front desk can help you.)</span>
                    <br />
                    <asp:CheckBox ID="Interview" runat="server" name="Services" Text="Interview with an Employer"/>&nbsp;
                    <span class="style4">(No appointment necessary)</span>
                    <br />
<%--onclick="ShowHideSeeSuccessCoach(this.id);"  --%>
                    <asp:CheckBox ID="SeeSuccessCoach" runat="server" name="Services" 
                        Text="To see my Success Coach: " 
                        CausesValidation="True" />
                    <span style="margin-left:20px;" />
                    <asp:Label runat="server" ID="lblCaseManager" Text="For which program?" />
                    <asp:DropDownList ID="ddlCaseManager" runat="server" 
                        Onchange="document.getElementById('SeeSuccessCoach').checked = Boolean(this.selectedIndex);" >
                        <asp:ListItem></asp:ListItem>
                        <asp:ListItem Value="BDS" Text="BDS - Business Development Specialist" />
                        <asp:ListItem Value="REA" Text="Reemployment and Eligibility Assessment" />
                        <asp:ListItem Value="SNAP" Text="Supplemental Nutrition Assistance Program" />
                        <asp:ListItem Value="TAA" Text="Trade Adjustment Act" />
                        <asp:ListItem Value="TTW" Text="Ticket-to-Work" />
                        <asp:ListItem Value="Vet" Text="Veteran" />
                        <asp:ListItem Value="WIA" Text="Workforce Investment Act" />
                        <asp:ListItem Value="WP" Text="Wagner-Peyser" />
                        <asp:ListItem Value="WTP" Text="Welfare Transition Program" />
                    </asp:DropDownList>
                    <asp:RequiredFieldValidator ID="reqCaseManager" runat="server" 
                        ErrorMessage="Select a program" ControlToValidate="ddlCaseManager" 
                        ForeColor="Red" SetFocusOnError="True" Text="&bull;" />
                </td>
            </tr>


<script type='text/javascript'>
	//This code added 20120410 to make checkboxes function like radiobuttons.
	//Each CheckBox has class="radio" added for this function.
	//If I can't get this to work or use a different script remove this and the class="radio" from all of the CheckBoxes.
	//I removed class="radio" from the RadioButtons and added it in the code behind like so: VeteranServ.InputAttributes.Add("class", "radio")
	//Still doesn't work.
	$(function ()
	{
		$(".radio").click(function ()
		{
			if ($(this).is(":checked"))
			{
				if ($(this).is($(".radio").eq(2)))
				{
					$(this).siblings().each(function ()
					{
						this.checked = false;
					});
					$(".radio").eq(1).prop({
						checked: true
					});
				} else if ($(this).is($(".radio").eq(1)))
				{
					if (!$(".radio").eq(2).is(":checked"))
					{
						$(this).siblings().each(function ()
						{
							this.checked = false;
						});
					}
				} else
				{
					$(this).siblings().each(function ()
					{
						this.checked = false;
					});
				}
			}
		});
	}); 
</script>

Open in new window

0
 
ProculopsisCommented:
Originally OP stated
I've requested that this question be deleted for the following reason:

One expert took the question down a rabbit hole of asking me why I didn't design the project differently from the beginning instead of providing any suggestions related to my question. I need a fairly simple JavaScript solution not suggestions that the project should have had a different design from the beginning. I have no control over the 'feature creep' that happened between the initial design specifications and what it has evolved into. I just need to add functionality that is requested. I wish to re-submit the question without the non-relevant inputs from the one expert who responded with repeated unhelpful suggestions.

Rouchie's comment was unhelpful but it was followed by some useful contributions so it is unfair to claim "Not getting any help."
0
 
megninAuthor Commented:
Point 1:  The "useful contributions" worked in jsFiddle but not in ASP.Net.
Point 2:  Even within the jsFiddle environment they did not address my main question.
Point 3:  When I pointed out the one functionality that the jsFiddle code was still missing, related to my question, the "expert" disappeared.

IMHO that is "Not getting any help".
0
 
megninAuthor Commented:
Not getting any help.
0
Question has a verified solution.

Are you are experiencing a similar issue? Get a personalized answer when you ask a related question.

Have a better answer? Share it in a comment.

All Courses

From novice to tech pro — start learning today.