Archive for August, 2008

Today I have spend lot of time to get the values of each item of CheckBoxList using javascript. And finally I got success.

What I want to do is:

I have one CheckBoxList control that binds values at runtime from the database, and when I click on a button from the page, I want to get the values (Database Primary Key) from the CheckBoxList, but for the checked checkboxes only.

Here is the code, what I have achieved so far. This code works fine with IE 7, but I am not sure with the FireFox.

ASPX page: <asp:CheckBoxList ID="CheckBoxList1" runat="server" OnDataBound="CheckBoxList1_DataBound" >
<asp:ListItem Value="First1" Text="First" ></asp:ListItem>
<asp:ListItem Value="second2" Text="Second"></asp:ListItem>
</asp:CheckBoxList>
<asp:Button ID="Button1" runat="server" Text="Button" />
<script language="javascript" type="text/javascript">
function CheckItem()
{
var tbl = document.getElementById('<%= CheckBoxList1.ClientID %>').childNodes[0];
for(var i=0; i<tbl.childNodes.length;i++)
{
for(var k=0; k<tbl.childNodes[i].childNodes.length; k++)
{
if(tbl.childNodes[i].childNodes[k].nodeName == "TD")
{
var currentTD = tbl.childNodes[i].childNodes[k];
for(var j=0; j<currentTD.childNodes.length; j++)
{
if(currentTD.childNodes[j].nodeName == "SPAN")
{
var currentSpan = currentTD.childNodes[j];
for(var l=0; l<currentSpan.childNodes.length; l++)
{
if(currentSpan.childNodes[l].nodeName == "INPUT" && currentSpan.childNodes[l].type == "checkbox")
{
var currentChkBox = currentSpan.childNodes[l];
if(currentChkBox.checked)
{
alert(currentSpan.alt);
}
}
}
}
}
}
}
}
}
</script>

Code Behind:

Button1.Attributes.Add("onclick", "javascript:CheckItem();");
CheckBoxList1.DataSource = <Your Dataset>;
CheckBoxList1.DataTextField = "PersonName";
CheckBoxList1.DataValueField = "PersonID";
CheckBoxList1.DataBind();
protected void CheckBoxList1_DataBound(object sender, EventArgs e)
{
CheckBoxList chkList = (CheckBoxList)(sender);
foreach (ListItem item in chkList.Items)
{
item.Attributes.Add("alt", item.Value);
}
}

Here I have provided a solution to put a counter for a textbox, that can be updated as each character typed into the textbox. This script will also validate the maximum character length allowed for a textbox. This script will also work when anyone copy/paste the text into the textbox. Textbox can be either single line or multi line. Check the following script:
<body>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="TextBox1" TextMode="multiLine" MaxLength="100" runat="server" onkeyup="javascript:CharCounter(this.id);" onblur="javascript:CharCounter(this.id);"></asp:TextBox>
<asp:Label ID="Label1" runat="server" Text="100 chars remaining"></asp:Label>
</div>
<script language="javascript" type="text/javascript">
function CharCounter(textId)
{
var totalchar = '<%= TextBox1.MaxLength %>';
var txtbox = document.getElementById(textId);
var lbl = document.getElementById('<% =Label1.ClientID %>');
if(txtbox.value.length > totalchar)
{
txtbox.value = txtbox.value.substring(0,totalchar);
}
lbl.innerText = (totalchar - txtbox.value.length) + " chars remaining" ;
}
</script>
</form>
</body>

Happy Coding!!

CustomValidator is a very useful control that can be used for client side as well as server side validation for the code. There might be some requirement on the server side to check some conditions and perform some action. Here, I have provided one example of the CustomValidator to check the server side as well as client side code.

To check the server side method/function using CustomValidator, you need to provide a server method name to the property “OnServerValidate” (i.e. OnServerValidate = “MyServerMethod”), and for client side code you can set the client method name to the property “ClientValidationFunction” (i.e. ClientValidationFunction = “MyClientMethod”).

On a button click event code, first you need to check the condition for Page.IsValid, as server side method will set Page.IsValid = false when a condition is not matched as requirement and hence will throw the message written in a CustomValidator control. The client side code will be executed first and if it executes successfully with valid arguments, then only the server side method will be checked further.

Check the following code which describes how to use CustomValidator.

<%@ Page Language="C#" AutoEventWireup="True" %>
<html>
<head>
<script runat="server">
void ValidateBtn_OnClick(object sender, EventArgs e)
{
if (Page.IsValid)
{
lblOutput.Text = "Page is valid.";
}
else
{
lblOutput.Text = "Page is not valid!";
}
}
void ServerValidation (object source, ServerValidateEventArgs arguments)
{
int i = int.Parse(arguments.Value);
arguments.IsValid = ((i%2) == 0);
}
</script>
</head>
<body>
<form runat="server">
<h3>CustomValidator Example</h3>
<asp:Label id=lblOutput runat="server"
Text="Enter an even number:"
Font-Name="Verdana"
Font-Size="10pt" /><br>
<p />
<asp:TextBox id="Text1"
runat="server" />
&nbsp;&nbsp;
<asp:CustomValidator id="CustomValidator1"
ControlToValidate="Text1"
ClientValidationFunction="ClientValidate"
OnServerValidate="ServerValidation"
Display="Static"
ErrorMessage="Not an even number!"
ForeColor="green"
Font-Name="verdana"
Font-Size="10pt"
runat="server"/>
<p />
<asp:Button id="Button1"
Text="Validate"
OnClick="ValidateBtn_OnClick"
runat="server"/>
</form>
</body>
</html>
<script language="javascript">
<!--
function ClientValidate(source, arguments)
{
if ((arguments.Value % 2) == 0)
arguments.IsValid=true;
else
arguments.IsValid=false;
}
// -->
</script>

How to manage a radio button in a Gridview? I have tried to select a single radio button out of multiple radio buttons in a Gridview. You can perform this using two ways. The first one is to use server side code. Use checked change property of radio button and find out which radio button has raised the event? and select that radio button; and make others uncheck. You need to set the “AutoPostBack” property of radio button to true to handle “OnCheckedChanged” event.

However, the another way to do is by using javascript. You need to write the following javascript in an aspx page where you are using your Gridview.


function CheckOnOff(rdoId,gridName)
{
    var rdo = document.getElementById(rdoId);
    /* Getting an array of all the "INPUT" controls on the form.*/
    var all = document.getElementsByTagName("input");
    for(i=0;i<all.length;i++)
    {  
        /*Checking if it is a radio button, and also checking if the
        id of that radio button is different than "rdoId" */
        if(all[i].type=="radio" && all[i].id != rdo.id)
        {
            var count=all[i].id.indexOf(gridName);
            if(count!=-1)
            {
               all[i].checked=false;
            }
        }
     }
     rdo.checked=true;/* Finally making the clicked radio button CHECKED */
}

You have to set the following properties of a radio button in a Gridview, to allow this script run properly.

<asp:GridView ID="myGrid" runat="server" AutoGenerateColumns="false" >
    <Columns>
        <asp:TemplateField HeaderText="Select">
            <ItemTemplate>
                <asp:RadioButton id="rdobutton"  runat="server" OnClick="javascript:CheckOnOff(this.id,'myGrid');"></asp:RadioButton>           </ItemTemplate>
        </asp:TemplateField>
    </Columns>
</asp:GridView>