Question

Uncheck last item checked in a CheckBoxList

Asked by: quanmac

I am trying to uncheck the last item checked of a checkboxlist when there are more than a certain number of items checked.

On the CheckBoxList:
chkAns.Attributes.Add("onclick", "CheckForTotalClicks('" + chkAns.ClientID + "', 3);");

When I check off a 4th item, the alert box didn't pop up and the 4th checked item doesn't get unchecked.

Any suggestions?

<script language="JavaScript" type="text/javascript">
<!--
    function CheckForTotalClicks(sourceId, totalClicks) 
    {
        //Check for total number of clicks
        var count = 0;
        var els = document.getElementsByTagName('input');
        var checkedItems = new Array();
        for (var i = 0; i < els.length; ++i) {
            var e = els[i];
            if (e.type == 'checkbox' && e.checked && (e.name.indexOf(sourceId) >= 0)) 
            {
                ++count;
                checkedItems.push(e.name);
            }
        }
        if (count > totalClicks) {
            alert('Please select up to ' + totalClicks + ' topics');
            var unCheck = document.getElementsByName(checkedItems.pop());
            unCheck.item.checked = false;
        }   
    }
-->
</script>

                                  
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:

Select allOpen in new window

This Question has been solved and asker verified All Experts Exchange premium technology solutions are available to subscription members.

Subscribe now for full access to Experts Exchange and get

Instant Access to this Solution

  • Plus...
  • 30 Day FREE access, no risk, no obligation
  • Collaborate with the world's top tech experts
  • Unlimited access to our exclusive solution database
  • Never be left without tech help again

Subscribe Now

Asked On
2009-09-01 at 10:09:16ID24698669
Tags

.NET

,

C#

,

CheckBoxList

,

Javascript

Topics

Programming for ASP.NET

,

C# Programming Language

,

.NET Framework 2.x

Participating Experts
3
Points
500
Comments
14

Trusted by hundreds of thousands everyday for fast, accurate and reliable tech support.

  • "The time we save is the biggest benefit of Experts Exchange to Warner Bros. What could take multiple guys 2 hours or more each to find is accessed in around 15 minutes on Experts Exchange." Mike Kapnisakis, Warner Bros.
  • "Our team likes having a resource that is more secure than just using Google and most experts using this service really know their stuff. It's nice to look here first versus using Google." Dayna Sellner, Lockheed Martin
  • "Anytime that I've been stumped with a problem, 9 out of 10 times Experts Exchange has either the accepted solution or an open discussion of the potential solution to the problem." Kenny Red, eBay Inc.

See what Experts Exchange can do for you.

Got a question?

We've got the answer.

Experts Exchange has been collecting answers to technology questions since 1996…3 million and counting! If you have a question, chances are we already have your answer.

Screenshot of Experts Exchange Knowledgebase

Need individual assistance?

Our experts are ready to help.

If you can't find the exact answer you're looking for, ask our exclusive community of 50,000 experts. You’ll get a personalized answer from a trusted professional.

Screenshot of Experts Exchange Knowledgebase

Want to learn from the best?

Read articles from industry experts.

Thousands of free tech tips, tricks, how-to’s and tutorials are available in our peer reviewed articles section. See for yourself how smart our experts are, no login required.

Screenshot of an Article

Working on a long term project?

Store your work and research.

Save solutions to your questions, answers you’ve discovered through searching plus helpful articles in your personal knowledgebase for easy future access.

Screenshot of Experts Exchange Knowledgebase

Access the answers to your technology questions today.

Subscribe Now

30-day free trial. Register in 60 seconds.

What Makes Experts Exchange Unique?

Members of the expert community talk about why the experience at Experts Exchange is different than what you will find anywhere else.

Trusted by the world's most respected brands.

image of each brand's logo

Faithfully serving IT professionals since 1996.

Experts Exchange Logo

Try it out and discover for yourself.

Subscribe Now

30-day free trial. Register in 60 seconds.

Related Solutions

  1. ASP.NET:  CheckBoxList ListItem
    [VB.NET] I have a CheckBoxList with AutoPostBack turned on and a handler server-side which is working just great. That means that .NET is handling the PostBacks itself, using its __doPostBack() JavaScript function. Each ListItem (which render as inputs) has "onclick&q...
  2. how to check and unchecked checkboxlist using javascript
    Hello experts, I have a check box (labeled Select all) and a checkboxlist. What I want to do is when I checked the checkbox, my bunch of checkboxlist will be checked and will be unchecked if I unchecked the checkbox. I have easily done using server-side script. But I'm t...
  3. Checkboxlist
    Hi, I have checkboxList control in a form with the follwoing data 1,2,3,4,5 and 6 (values and texts) in a table column I have only 1,3 and 5 How can I set 1,3 and 5 as selected in the checkboxlist in the page load event. ayha
  4. Checkboxlist in Javascript
    Hello, I have got a checkboxlist in asp.net 2.0 with items populating from Database. After populating items from Database. I'm insert a new item "Select All" into to the checkboxlist. I need actually, a javascript help. When I'm checking the "Select All&quo...
  5. limit checkboxlist selected items
    I have a .net <asp:checkboxlist> with about 20 listitems. I need to make it so the user can only select 2 items at a time. Then, I need to post the results to a results page.

Free Tech Articles

  1. WARNING: 5 Reasons why you should NEVER fix a computer for free.
    It is in our nature to love the puzzle. We are obsessed. The lot of us. We love puzzles. We love the challenge. We thrive on finding the answer. We hate disarray. It bothers us deep in our soul. W...
  2. SCCM OSD Basic troubleshooting
    SCCM 2007 OSD is a fantastic way to deploy operating systems, however, like most things SCCM issues can sometimes be difficult to resolve due to the sheer volume of logs to sift through and the dispe...
  3. Migrate Small Business Server 2003 to Exchange 2010 and Windows 2008 R2
    This guide is intended to provide step by step instructions on how to migrate from Small Business Server 2003 to Windows 2008 R2 with Exchange 2010. For this migration to work you will need the fo...
  4. Create a Win7 Gadget
    This article shows you how to create a simple "Gadget" -- a sort of mini-application supported by Windows 7 and Vista. Gadgets can be dropped anywhere on the desktop to provide instant information, ...
  5. Outlook continually prompting for username and password
    There have been a lot of questions recently regarding Outlook prompting for a username and password whilst using Exchange 2007. There are a few reasons why this would happen and I will try to cover t...
  6. Backup Exchange 2010 Information Store using Windows Backup
    There seems to be quite a lot of confusion around the ability to backup Exchange 2010 using the built in Windows Backup feature. This stems from the omission of this feature prior to Exchange 2007 s...

Cloud Class Webinars

  1. Avoiding Bugs in Microsoft Access
    Alison Balter takes and in-depth look at avoiding bugs in Access. In this webinar you will learn about using the immediate window to debug your applications, invoking the debugger, using breakpoints to troubleshoot, stepping through code, setting the next statement to execute, ...
  2. Top 10 Best New Features in Visio 2010
    Scott Helmers gives live demonstrations of the top 10 new features in Visio 2010. This webinar will teach you how to create compelling diagrams by adding shapes to the page with a single click, linking the shapes in a diagram to data in Excel (or SQL Server, or SharePoint), ...
  3. IT Consultant Business Secrets Revealed
    Michael Munger, Experts Exchange tech pro and IT consultant, pulls back the curtain on his very successful businesses and answers question on every IT consultant and business owner should know about. He shares secrets on what he did to solve the 5 most common problems in IT, ...
  4. Disaster Recovery and Business Continuity
    Quest CTO, Mike Billon, gives an overview of the steps involved in building a dunamic disaster recovery plan. Through case studies and an examination of software/hardware tooles for monitoring and testing, you'll gain a better understandin of where you are, where you want ...
  5. Organize Your Visio Diagrams with Containers and Lists
    Scott Helmers uses cross functional flowcharts, wireframe diagrams, data graphic legends and seating charts to teach you: how to ustilize all three new structured diagram components in Visio 2010, the best practices for organizeing shapes in previous version of Visio, how to organize ...
  6. How to Us Objects, Properties, Events and Methods in Microsoft Access
    Alison Dalter gives an in-depbth look at objects, properties, events and methods in Microsoft Access. In this webinar you will learn about using the object browser, referring to objects, working with properties and methods, working with object variables, understanding the ...

Join the Community

Give a Little. Get a Lot.

Join the community of experts here and help other tech pros by answering question in your area of expertise. You can earn FREE access to all Experts Exchange's premium features and resources.

Join the Community

Answers

 

by: quanmacPosted on 2009-09-01 at 10:10:47ID: 25233658

I've also tried:

unCheck.checked = false;

in the javascript and it still didn't work.

 

by: NeilsrPosted on 2009-09-01 at 10:19:24ID: 25233736

From Article http://www.experts-exchange.com/Programming/Languages/.NET/ASP.NET/Q_21095389.html

============
Well, here's another try.  This might work, but only IE supports this syntax.  If it works, a similar solution can be made to support other browsers.

Two possible ways of going at it:

1. Give your single unique checkbox an id.
<asp:ListItem id="SpecialCheckbox"...>

Then in the <head> section of your aspx page, add the following client-side script block:
<script for="SpecialCheckbox" event="onclick">
window.cancelEvent = true; // avoid the postback
var chk = event.srcElement;
alert( chk.checked ); // just to see that it works
</script>

2. This is a better solution for generated list items (i.e., made at run-time in your code-behind or other scriptblock):
Give all your listitems the same id, and also give them an attribute that identifies them in addition.
So the result html could look like:
<input type="checkbox" name="MyCheckboxList" specialId="1">
<input type="checkbox" name="MyCheckboxList" specialId="2">
<input type="checkbox" name="MyCheckboxList" specialId="3">

And then in the same client-side script block:
<script for="SpecialCheckbox" event="onclick">
var chk = event.srcElement;
alert( chk.checked ); // just to see that it works
if( chk.specialId == '3' ) {
  event.cancelEvent = true; // avoid the postback
  // do stuff
}
</script>


If these don't work, you can try some variation.  Maybe this will give you a better direction.

Btw, have you considered that a better solution may be to avoid using a CheckBoxList?  You can use a DataRepeater to render all your checkboxes in a similar way, and this gives you more flexibility for particular treatment of special checkboxes.

 

by: HonorGodPosted on 2009-09-01 at 10:39:56ID: 25233913

Something like this perhaps?

<html>
<body>
 
1 <input type='checkbox'><br>
2 <input type='checkbox'><br>
3 <input type='checkbox'><br>
4 <input type='checkbox'><br>
<script type="text/javascript">
function last() {
  var inputs = document.getElementsByTagName( 'INPUT' );
  for ( var i = inputs.length - 1; i > 0; i-- ) {
    var input = inputs[ i ];
    if ( input.type == 'checkbox' ) {
      input.checked = false;
      break;
    }
  }
}
</script>
<input type='button' value='Last' onclick='last()'>
 
</body>
</html>

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:

Select allOpen in new window

 

by: ddayx10Posted on 2009-09-01 at 11:14:25ID: 25234277

I tend to want to stand this problem on it's head to make it easier to solve. I really dont want to try to debug your code. I would solve this problem by changing my assignment of the javascript onclick event to the items of the checkboxlist control instead of the control itself. This gives me a very easy way of tracking which input called the function and therefore which was the last to be previously checked.

Works great!

So (see example):

****ASPX SMPL Page w/JavaScript****
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
 
<!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>Managing CheckBoxList</title>
    <script type="text/javascript">
		
		var previouslyCheckedInput;
		
		function manageCheckBoxes(parent, source, maxChecked)
		{
			var inputsChecked = 0;
			var inputCollection = parent.getElementsByTagName('input');
			
			for(i=0;i<inputCollection.length;i++)
			{
				if(inputCollection[i].checked)
				{ inputsChecked ++; }
			}
 
			if(inputsChecked > maxChecked)
			{
				previouslyCheckedInput.checked = false;
			}
			
			previouslyCheckedInput = source;
		}
    
    </script>
</head>
<body>
    <form id="form1" runat="server">
 
		<asp:CheckBoxList ID="chkBoxL" runat="server">
			<asp:ListItem Text="Option1" Value="1" />
			<asp:ListItem Text="Option2" Value="2" />
			<asp:ListItem Text="Option3" Value="3" />
			<asp:ListItem Text="Option4" Value="4" />
			<asp:ListItem Text="Option5" Value="5" />
		</asp:CheckBoxList>
 
    </form>
</body>
</html>
 
 
****CODE BEHIND****
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            foreach (ListItem l in chkBoxL.Items)
            { l.Attributes.Add("onclick", "manageCheckBoxes(" + chkBoxL.ClientID + ",this,3);"); }
        }
    }

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:

Select allOpen in new window

 

by: HonorGodPosted on 2009-09-01 at 11:37:25ID: 25234566

ah.  Now I see what you are talking about...

Something like this perhaps?

<html>
<head>
<script type="text/javascript">
function LE( obj, limit ) {
  if ( obj.checked ) {
    var inputs = document.getElementsByTagName( 'INPUT' );
    for ( var i = 0; i < inputs.length; i++ ) {
      var input = inputs[ i ];
      if ( ( input.type == 'checkbox' ) && ( input.checked ) ) {
        if ( limit > 0 ) {
          limit--;
        } else {
          obj.checked = false;
          break;
        }
      }
    }
  }
}
</script>
</head>
<body>
 
1 <input type='checkbox' onchange='LE(this, 2)'><br>
2 <input type='checkbox' onchange='LE(this, 2)'><br>
3 <input type='checkbox' onchange='LE(this, 2)'><br>
4 <input type='checkbox' onchange='LE(this, 2)'><br>
 
</body>
</html>

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:

Select allOpen in new window

 

by: ddayx10Posted on 2009-09-01 at 11:48:23ID: 25234672

If I understood the problem correctly he wants a max number of inputs allowed checked. If a newly checked input exceeds the limit he wants to unselect the input that was checked previous to the current selection?!! Maybe I misunderstood the problem, but that's what the code sample I wrote above does...alas I dunno anymore and until user gets a chance to look at everything and comment I'm gonna chill.

I think maybe I overthought this, but it's even easier if he just wants the last one selected to be unchecked. Just change the above code provided by two lines.

    <script type="text/javascript">
		
	
		function manageCheckBoxes(parent, source, maxChecked)
		{
			var inputsChecked = 0;
			var inputCollection = parent.getElementsByTagName('input');
			
			for(i=0;i<inputCollection.length;i++)
			{
				if(inputCollection[i].checked)
				{ inputsChecked ++; }
			}
 
			if(inputsChecked > maxChecked)
			{
				source.checked = false;
                                    //fire some alert msg if you want
			}
 
		}
    
    </script>
                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:

Select allOpen in new window

 

by: quanmacPosted on 2009-09-01 at 11:57:56ID: 25234761

ddayx10, yes you understood my problem.

I tried running your code and it gave me a javascript error:

Message: 'chkList104677' is undefined
Line: 305
Char: 1
Code: 0

seems to be having a problem with the source

 

by: ddayx10Posted on 2009-09-01 at 12:29:05ID: 25235049

Well I took advantage of an IE quirk in sending the ClientID to the JS function. It worked in IE but not so good in Firefox. I shoulda checked that. I don't get the same error as you, but I did get an error in FF. I modified the code behind and the JS slightly to correct this. Otherwise I've tested this in both browsers without any problems...hope it works for you :)

PS: When you say I understood the problem:
A) You want the previously selected input to uncheck, leaving the most recently selected input checked?
OR
B) Just stop the last check from happening if its over the limit?

Either way I think I showed you above how to manage both ways.

*****ASPX PAGE****
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
 
<!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>Managing CheckBoxList</title>
    <script type="text/javascript">
		
		var previouslyCheckedInput;
		
		function manageCheckBoxes(parentID, source, maxChecked)
		{
			var inputsChecked = 0;
			var parent = document.getElementById(parentID);
			var inputCollection = parent.getElementsByTagName('input');
			
			for(i=0;i<inputCollection.length;i++)
			{
				if(inputCollection[i].checked)
				{ inputsChecked ++; }
			}
 
			if(inputsChecked > maxChecked)
			{
				previouslyCheckedInput.checked = false;
			}
			
			previouslyCheckedInput = source;
		}
    
    </script>
</head>
<body>
    <form id="form1" runat="server">
 
		<asp:CheckBoxList ID="chkBoxL" runat="server">
			<asp:ListItem Text="Option1" Value="1" />
			<asp:ListItem Text="Option2" Value="2" />
			<asp:ListItem Text="Option3" Value="3" />
			<asp:ListItem Text="Option4" Value="4" />
			<asp:ListItem Text="Option5" Value="5" />
		</asp:CheckBoxList>
 
    </form>
</body>
</html>
 
 
****CODE BEHIND****
public partial class Default2 : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            foreach (ListItem l in chkBoxL.Items)
            { l.Attributes.Add("onclick", "manageCheckBoxes('" + chkBoxL.ClientID + "',this,3);"); }
        }
    }
}

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:

Select allOpen in new window

 

by: HonorGodPosted on 2009-09-01 at 12:33:32ID: 25235096

The function LE() (i.e., Less Than, or Equal To) in http:#a25234566
allows you to specify the maximum number of "checked" boxes.  If you try to check one more, it will get cleared.

Is this what you want?

 

by: quanmacPosted on 2009-09-01 at 12:40:03ID: 25235147

Just stop the last check from happening if its over the limit

That is what I need the script to do.

I've had to re-write some of the script code from ddayx10 to get rid of the javascript errors I was getting.

The errors I was getting was that it wasn't able to find the source element because it was missing: "ctl111_" in front of the element name. That's why I had do use indexOf to find the element name.

The alert box pops up, but I'm unable to get the last checked item to be unchecked when it goes over the limit.

Code Behind:
itm.Attributes.Add("onclick", "CheckForTotalClicks('" + chkAns.ClientID + "', '" + chkAns.ClientID + "_" + count + "', " + EvalQuestion.courEvalQTotalSelectableOptions + ")");
 
Javascript:
function CheckForTotalClicks(parent, source, maxChecked) 
    {
        //Check for total number of clicks
        var count = 0;
        var inputCollection = document.getElementsByTagName('input');
        var sourceName;
        for (i = 0; i < inputCollection.length; i++) {
            var e = inputCollection[i];
            if (e.type == 'checkbox' && e.checked && (e.name.indexOf(parent) >= 0)) 
            {
                count++;
                if (e.name.indexOf(source) >= 0) { sourceName = e.name; }
            }
        }
        if (count > maxChecked) {
            alert('Please select up to ' + maxChecked + ' topics');
            var src = document.getElementsByName(sourceName);
            src.checked = false;
        }
    }

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:

Select allOpen in new window

 

by: quanmacPosted on 2009-09-01 at 13:05:03ID: 25235396

So after a few more modifications, I've finally was able to get the script to work the way I want it to.

Although I don't think it is very efficient, but it is a working version and I can finally move on.

If you have suggestions on how to make it more efficient please post you solutions and I will take a look.

Thanks ddayx10, your posts definately helped me figure this out. Sorry HonorGod, I was never able to try out your code.

function CheckForTotalClicks(parent, source, maxChecked) 
    {
        //Check for total number of clicks
        var count = 0;
        var inputCollection = document.getElementsByTagName('input');
        for (i = 0; i < inputCollection.length; i++) {
            var e = inputCollection[i];
            if (e.type == 'checkbox' && e.checked && (e.name.indexOf(parent) >= 0)) 
            {
                count++;
            }
        }
        for (j = 0; j < inputCollection.length; j++) 
        {
            var unCheck = inputCollection[j];
            if (unCheck.type == 'checkbox' && unCheck.checked && (unCheck.name.indexOf(parent) >= 0)) {
                if (count > maxChecked && unCheck.name.indexOf(source) >= 0) {
                    alert('Please select up to ' + maxChecked + ' topics');
                    unCheck.checked = false;
                }
            }
        }
    }

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:

Select allOpen in new window

 

by: ddayx10Posted on 2009-09-01 at 13:20:56ID: 25235572

Well I have lots of thoughts about this, but to your one issue I think it may be here:

Your issue:
The alert box pops up, but I'm unable to get the last checked item to be unchecked when it goes over the limit.

Initial problem I see:
var src = document.getElementsByName(sourceName);

This is a collection in the current form and if you wanted to get your hands on an item in the collection you would need to supply an index which is likely 0 if you've gotten it right.:
var src = document.getElementsByName(sourceName)[index];

I'm not sure if that's going to make everything work out. The approach you've chosen is unusual. Some things are clearly unnecessary and even making things harder. Let's see if I can explain.


*****************************
l.Attributes.Add("onclick", "manageCheckBoxes('" + chkBoxL.ClientID + "',this,3);");


function manageCheckBoxes(parentID, source, maxChecked)
1) ParentID is going to be the clientID assigned to the checkboxlist (which will include the ctl_00_whatever nonsense). This can be used to get the actual checkboxlist (which is actually a <table>)

2) source is being assigned from the"this" keyword and is the input that was last clicked.

3) maxChecked I think is obvious.


Now, you're doing this:
var inputCollection = document.getElementsByTagName('input');

And I'm doing this:
var parent = document.getElementById(parentID);
var inputCollection = parent.getElementsByTagName('input');

Doing it your way requires all the e.type checking. My way only returns the inputs as a collection that are part of the checkboxlist (parent).

Trying to get the name of the input is just a mistake. If you pass in the "this" keyword. You don't have to find the element that was last clicked at all, you just have to call source.checked = false;

I appreciate that there was an error in my original code, but I have triple checked it and it works fine. I've made the modifications, and some comments that match to just remove the last item checked. I'll post it one more time and you can choose. I'm sorry if I made it harder for you.

****CODE BEHIND****
foreach (ListItem l in chkBoxL.Items)
{ l.Attributes.Add("onclick", "manageCheckBoxes('" + chkBoxL.ClientID + "',this,3);"); }
 
 
***ASPX PAGE****
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default2.aspx.cs" Inherits="Default2" %>
 
<!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>Managing CheckBoxList</title>
    <script type="text/javascript">
		
		var previouslyCheckedInput;
		
		//parentID = id assigned to the checkboxlist by asp.net
			//- used to get collection of inputs in checkboxlist
		//source = <input> element that was last checked, causing the function to be called
		//maxChecked = max number of inputs allowed checked
		function manageCheckBoxes(parentID, source, maxChecked)
		{
			var inputsChecked = 0; //counter for # inputs checked
			var parent = document.getElementById(parentID); //checkboxlist
			
			//by calling getElementsByTagName on the checkboxlist itself we only
			//get the checkboxes that are included, not all inputs on the page
			//we know these are all input of type "checkbox" so we dont have to evaluate that.
			var inputCollection = parent.getElementsByTagName('input');
			
			//simply counts the number of inputs in the checkboxlist that are checked
			for(i=0;i<inputCollection.length;i++)
			{
				if(inputCollection[i].checked)
				{ inputsChecked ++; }
			}
 
			//if we have more inputs selected than the max we use the "source" paremeter
			//(which is the this keyword, and therefore the input that cause the event to fire)
			//to uncheck the last input selected
			if(inputsChecked > maxChecked)
			{
				source.checked = false;
			}
		}
    
    </script>
</head>
<body>
    <form id="form1" runat="server">
 
		<asp:CheckBoxList ID="chkBoxL" runat="server">
			<asp:ListItem Text="Option1" Value="1" />
			<asp:ListItem Text="Option2" Value="2" />
			<asp:ListItem Text="Option3" Value="3" />
			<asp:ListItem Text="Option4" Value="4" />
			<asp:ListItem Text="Option5" Value="5" />
		</asp:CheckBoxList>
 
    </form>
</body>
</html>

                                              
1:
2:
3:
4:
5:
6:
7:
8:
9:
10:
11:
12:
13:
14:
15:
16:
17:
18:
19:
20:
21:
22:
23:
24:
25:
26:
27:
28:
29:
30:
31:
32:
33:
34:
35:
36:
37:
38:
39:
40:
41:
42:
43:
44:
45:
46:
47:
48:
49:
50:
51:
52:
53:
54:
55:
56:
57:
58:
59:
60:
61:
62:
63:

Select allOpen in new window

 

by: ddayx10Posted on 2009-09-01 at 13:25:33ID: 25235625

Cool I see you worked it out while I was typing a lengthy thing above...glad you got it.

 

by: HonorGodPosted on 2009-09-06 at 15:47:38ID: 25271908

Thanks for the assist and the points.

Good luck & have a great day.

20120131-EE-VQP-002

3 Ways to Join

30-Day Free Trial

The Experts

98% positive feedback on 31,087 answers since March 2000. angeliii is a Microsoft Most Valuable Professional for his work with MS SQL Server & Develoment.

He has also proven his knowledge of Visual Basic Programming, PHP Scripting and Oracle Databases.

The Experts

97% positive feedback on 10,752 answers since July 2000. lrmoore has more than 18 years experience in the networking industry.

The six-time Mircosoft MVPs specialties include firewalls, virtual private networking, and network management.

Testimonials

"...and excellent source for support... Kind of like having your very own IT dept." Electriciansnet

Testimonials

"I was apprehensive at signing up at first. However... it has already made my life as an IT administrator much easier." JaCrews

Testimonials

"WOW! You guys have great, active, and knowledgeable people on here." moore50

Business Clients

Business Clients

In the Press

"If you’ve got a question... Experts Exchange can supply an answer.”

In the Press

"...an invaluable aid for both IT professionals and those who require tech support."

In the Press

"where IT professionals provide quick answers on just about any topic"

Business Account Plans

Loading Advertisement...