现在的位置: 首页 > 综合 > 正文

jQuery获取动态生成checkboxlist的value值

2013年09月07日 ⁄ 综合 ⁄ 共 2316字 ⁄ 字号 评论关闭

 

jQuery获取checkboxlist的value值

CheckboxList是服务器控件,绑定数据容易,服务器端获取选中值也容易。但是生成的静态页面没有ListItem的Value值,所以默认情况下用js在页面中是取不到ListItem的值的。

问题描述:js取不到选中的ListItem的值。

 

<asp:CheckBoxList
runat="server"
ID="listTest">

</asp:CheckBoxList>
<input
type="button"
id="btnShow"
value="显示选中值"
/>

 

下面是生成的静态html:

 

<table id="listTest"
border="0">

<tr>
   <td>
       <input
id="listTest_0"
type="checkbox"
name="listTest$0"
/>

       <label
for="listTest_0">
基于jQuery的一个震动效果</label>
   </td>
   </tr>
<tr>
   <td><input
id="listTest_1"
type="checkbox"
name="listTest$1"
/>

       <label
for="listTest_1">
使用css的overflow属性改变缩略图大小</label>
   </td>
</tr>
</table>

 

解决方法:

在绑定checkboxlist时,为ListItem每个对象添加一个alt属性,值保存对应的value值,代码如下:

if (dt != null && dt.Rows.Count >
0)
{
   foreach (DataRow dr
in dt.Rows)
    {
       //分别为text值、value值
        listTest.Items.Add(new ListItem(dr["Title"].ToString(), dr["ID"].ToString()));
    }
   //为ListItem对象添加alt属性,值保存value值
   foreach (ListItem li
in listTest.Items)
    {
        li.Attributes.Add("alt", li.Value);
    }
}

//第二种
protected void chkbind()
    {
        string sel = "select Product_id,ProductName from Product";
        SqlDataReader dr = sqlHelper.ExecuteReader(sqlHelper.conn, CommandType.Text, sel, null);
        chkProduct.DataTextField = "ProductName";
        chkProduct.DataValueField = "Product_id";
        chkProduct.DataSource = dr;
        chkProduct.DataBind();
        conn.Close();
        foreach (ListItem li in chkProduct.Items)
        {
            li.Attributes.Add("alt", li.Value);
        }
    }

<table
id="Table1"

border="0">

<tr>
<td>
   <span
alt="400"
>
<input
id="listTest_0"
type="checkbox"
name="listTest$0"
/>

   <label
for="listTest_0"
>
基于jQuery的一个震动效果</label></span>
</td>
</tr>
<tr>
<td><span
alt="398">
<input
id="listTest_1"
type="checkbox"
name="listTest$1"
/>

<label for="listTest_1">使用css的overflow属性改变缩略图大小</label></span>
</td>
</tr>
</table>


下面就是js取选中的listitem的值:

 

$(document).ready(function() {
    $("#btnShow").click(function() {
       var valuelist =
"";
//保存checkbox选中值
       //遍历name以listTest开头的checkbox
        $("input[name^='listTest']").each(function()
{

           if (this.checked) {
               //$(this):当前checkbox对象;
               //$(this).parent("span"):checkbox父级span对象
                valuelist += $(this).parent("span").attr("alt")
+ ",";
            }
        });
       if (valuelist.length >
0) {
           //得到选中的checkbox值序列,结果为400,398
            valuelist = valuelist.substring(0, valuelist.length -
1);
        }
    });
});

抱歉!评论已关闭.