Web Developer Friend

Get CheckBoxList values using Javascript

Posted by: viralsarvaiya on: October 28, 2009

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);
}
}

 

other way is as below….

this is run in FF as well as FF

function CheckItem() {

var tbl = document.getElementById(‘<%= CheckBoxList1.ClientID %>’);

var chkspecialCount = tbl.getElementsByTagName(“input”);

var chkspeciallbls = tbl.getElementsByTagName(“label”);

for (var i = 0; i < chkspecialCount.length; i++) {

if (chkspecialCount[i].checked == true) {

var str = chkspeciallbls[i].innerHTML;

alert(str);

}

}

}

Enjoy Coding….

Reference

http://hspinfo.wordpress.com/2008/08/14/get-checkboxlist-values-using-javascript/

Leave a Reply

Blog Stats

  • 5,866 hits