jQuery获取动态生成checkboxlist的value值

 

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

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值