Aaron Li's Blog

Write it down before I forget

  Home  |   Contact  |   Syndication    |   Login
  30 Posts | 0 Stories | 21 Comments | 1 Trackbacks

News

Google

Archives

Other's Idea

Scenario:
I have a repeater with people’s name listed. Next to every name, there is a checkbox used to select people. Every time, only 2 people can be selected.
 
HTML portion,
 
<asp:Repeater ID="Repeater1" runat="server" EnableViewState = "false">
    <ItemTemplate>
        <asp:CheckBox ID="CheckBox1" runat="server" onclick="CheckedChanged(this.checked)" />
        <%#Eval("Name")%>
    </ItemTemplate>
</asp:Repeater>
<input id="TotalChecked" type="hidden" value="0"/>
 
Javascript is used to count how many people have been selected.
 
function getObj(name)
{
    if (document.getElementById) // test if browser supports document.getElementById
    {
        this.obj = document.getElementById(name);
    }
    else if (document.all) // test if browser supports document.all
    {
        this.obj = document.all[name];
    }
    else if (document.layers) // test if browser supports document.layers
    {
        this.obj = document.layers[name];
    }
}
 
function CheckedChanged(IsChecked)
{
    var objTotalChecked = new getObj('TotalChecked');
    var intTotalChecked = eval(objTotalChecked.obj.value);
    if (IsChecked)
    {
        objTotalChecked.obj.value = intTotalChecked + 1;
    }
    else
    {
        objTotalChecked.obj.value = intTotalChecked - 1;
    }
   
    if (objTotalChecked.obj.value >= 2 )
        alert("You can only talk to 2 people. Now you have selected " + objTotalChecked.obj.value +".");
}
 
In addition, when the page or part of the page is submitted, on server side, I would validate the total number of selected people.
posted on Sunday, June 17, 2007 6:59 PM

Feedback

# re: Checkbox Counter and JavaScript 11/20/2007 7:17 PM Aaron
I like to set EnableViewState="false" for most controls on a page, so that the page doesn't get too heavy.

As I mentioned in another post View State and TextBoxes, CheckBoxes, DropDownLists (
http://geekswithblogs.net/AaronLi/archive/2007/05/20/112615.aspx), control state is independent to view state; as a result, if you set the attribute [runat] to "server", checkbox's state can be kept during postbacks, no matter the viewstate for the repeater(or the checkbox) is true or false, and no matter it is a HTML checkbox or a .NET checkbox control.

If a HTML checkbox is used and the attribute [runat="server"] is not set, after the submission, the status of the checkboxes could not be recovered unless the selected values are kept by certain way, for example, a hidden field; then during databinding after submission, according to the hidden field's value, manually recover the status of the checkboxes.


Post A Comment
Title:
Name:
Email:
Website:
Comment:
Verification: