Solved

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

Posted on 2012-04-10
19
284 Views
Last Modified: 2012-08-14
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
0
Comment
Question by:megnin
  • 12
  • 4
  • 3
19 Comments
 
LVL 25

Expert Comment

by:Rouchie
Comment Utility
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
 
LVL 1

Author Comment

by:megnin
Comment Utility
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
 
LVL 25

Expert Comment

by:Rouchie
Comment Utility
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
 
LVL 25

Expert Comment

by:Rouchie
Comment Utility
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
 
LVL 1

Author Comment

by:megnin
Comment Utility
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
 
LVL 1

Author Comment

by:megnin
Comment Utility
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
 
LVL 20

Expert Comment

by:Proculopsis
Comment Utility
<!-- 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
 
LVL 25

Expert Comment

by:Rouchie
Comment Utility
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
 
LVL 1

Author Comment

by:megnin
Comment Utility
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
6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

 
LVL 20

Expert Comment

by:Proculopsis
Comment Utility
<!-- 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
 
LVL 1

Author Comment

by:megnin
Comment Utility
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
 
LVL 1

Author Comment

by:megnin
Comment Utility
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
 
LVL 1

Author Comment

by:megnin
Comment Utility
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
 
LVL 1

Author Comment

by:megnin
Comment Utility
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
 
LVL 1

Author Comment

by:megnin
Comment Utility
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
 
LVL 1

Accepted Solution

by:
megnin earned 0 total points
Comment Utility
I give up.
0
 
LVL 20

Expert Comment

by:Proculopsis
Comment Utility
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
 
LVL 1

Author Comment

by:megnin
Comment Utility
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
 
LVL 1

Author Closing Comment

by:megnin
Comment Utility
Not getting any help.
0

Featured Post

What Security Threats Are You Missing?

Enhance your security with threat intelligence from the web. Get trending threat insights on hackers, exploits, and suspicious IP addresses delivered to your inbox with our free Cyber Daily.

Join & Write a Comment

Just a quick little trick I learned recently.  Now that I'm using jQuery with abandon in my asp.net applications, I have grown tired of the following syntax:      (CODE) I suppose it just offends my sense of decency to put inline VBScript on a…
Boost your ability to deliver ambitious and competitive web apps by choosing the right JavaScript framework to best suit your project’s needs.
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…

771 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

7 Experts available now in Live!

Get 1:1 Help Now