問題
如何配合Client Button控制項取得CheckBoxList的值
解決方法
使用Javascript配合html的input button,處理方式是直接由Javascript以id取得CheckBoxList的控制項後,傳回已選擇的值
而前後者不同的是一個再Server端執行,一個則由Client處理完成,若網頁上的控制項很多,使用Server端的方式執行將會造成網路流量的增加,使用上須小心!
CheckBoxList控制項輸出到Client端的時候會像這樣參考
所以抓取的方式跟RadioButtonList是一樣的
.aspx如下:
<%@ Page Language="C#" AutoEventWireup="true" Codebehind="Default.aspx.cs" Inherits="WebApplication1._Default" %>
<!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>未命名頁面</title>
</head>
<script language="javascript">
//取得垂直排列的CheckBoxList值
function cilckbtnVertical()
{
var table;
var choiceitem="";
//取得並觸發按鍵動作
table=document.getElementById("CheckBoxList1");
for(i=0;i<table.rows.length;i++)
{
if(table.rows[i].cells[0].childNodes[0].checked == true)
{
selValue = table.rows[i].cells[0].childNodes[0].value;
choiceitem=choiceitem+" "+i;
}
}
if(choiceitem!="")
{
alert("已選擇:"+choiceitem);
}
}
//取得水平排列的CheckBoxList值
function cilckbtnHorizontal()
{
var table;
var choiceitem="";
//取得並觸發按鍵動作
table=document.getElementById("CheckBoxList1");
for(i=0;i<table.rows[0].cells.length;i++)
{
if(table.rows[0].cells[i].childNodes[0].checked == true)
{
selValue = table.rows[0].cells[i].childNodes[0].value;
choiceitem=choiceitem+" "+i;
}
}
if(choiceitem!="")
{
alert("已選擇:"+choiceitem);
}
}
</script>
<body>
<form id="form1" runat="server">
<div>
<asp:CheckBoxList ID="CheckBoxList1" runat="server">
</asp:CheckBoxList><%--按下btnServerCall的時候去Postback候傳回變更後的Textbox值--%>
<%--按下btnJavaScriptCall的時候去觸發javascript--%>
<input id="btnJavaScriptCall" type="button" value="JavaScriptChoice1" onclick="cilckbtnVertical();" />
<%--<input id="Button1" type="button" value="JavaScriptChoice1" onclick="cilckbtnHorizontal();" />--%>
</div>
</form>
</body>
</html>
.cs如下:namespace WebApplication1
{
public partial class _Default : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
if (!IsPostBack)
{
for (int i = 0; i <= 3; i++)
{
ListItem lt = new ListItem();
lt.Text = "選擇" + i.ToString();
lt.Value = i.ToString();
this.CheckBoxList1.Items.Add(lt);
}
}
}
}
}
沒有留言:
張貼留言