2010年5月29日 星期六

javascript取checkboxlist值

=====網頁======
<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Javascript_Checkbox.aspx.cs" Inherits="Javascript_Checkbox" %>

<!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>Javascript Selectted Item From CheckBoxList</title>

<script type="text/javascript">
function Get_Selected_Value()
{
var ControlRef = document.getElementById('<%= CheckBoxList1.ClientID %>');
var CheckBoxListArray = ControlRef.getElementsByTagName('input');
var spanArray=ControlRef.getElementsByTagName('span');
var checkedValues = '';
var nIndex=0;
var sValue='';

for (var i=0; i<CheckBoxListArray.length; i++)
{
var checkBoxRef = CheckBoxListArray[i];

if ( checkBoxRef.checked == true )
{
var labelArray = checkBoxRef.parentNode.getElementsByTagName('label');


if ( labelArray.length > 0 )
{
if ( checkedValues.length > 0 )
{
checkedValues += ', ';
nIndex += ', ';
sValue += ', ';
}
checkedValues += labelArray[0].innerHTML;
nIndex +=i;
sValue +=spanArray[i].alt;
}
}
}
document.getElementById('<%= lbl_SelectedValue.ClientID %>').innerHTML='<b>Selected Value:</b> '+ sValue;
document.getElementById('<%= lbl_SelectedText.ClientID %>').innerHTML='<b>Selected Text:</b> '+checkedValues;
document.getElementById('<%= lbl_SelectedIndex.ClientID %>').innerHTML='<b>Selected Index:</b> '+nIndex;
}
</script>

</head>
<body>
<form id="form1" runat="server">
<div>
<asp:CheckBoxList ID="CheckBoxList1" runat="server" onclick="Get_Selected_Value();" OnDataBound="CheckBoxList1_DataBound">
</asp:CheckBoxList>
<hr />
<label id="lbl_SelectedValue" runat="server"></label><br />
<label id="lbl_SelectedText" runat="server"></label><br />
<label id="lbl_SelectedIndex" runat="server"></label>
</div>
</form>
</body>
</html>

=====程式碼======
using System;
using System.Data;
using System.Configuration;
using System.Web.UI.WebControls;
using System.Data.SqlClient;

public partial class Javascript_Checkbox : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
string connectionString = ConfigurationManager.ConnectionStrings["TestConnection"].ConnectionString;
DataTable dt = new DataTable();
SqlConnection conn = new SqlConnection(connectionString);
using (conn)
{
SqlDataAdapter ad = new SqlDataAdapter(
"SELECT ID,Title from Article", conn);
ad.Fill(dt);
}
CheckBoxList1.DataSource = dt;
CheckBoxList1.DataTextField = "Title";
CheckBoxList1.DataValueField = "ID";
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);
}
}