解決無法用Javascript取得CheckBoxList Value的問題

本文介绍了一种方法,通过为ASP.NET中的CheckBoxList控件的每个项添加自定义属性来解决JavaScript无法直接获取其值的问题,并展示了如何使用jQuery进行值的读取。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

先放置一個測試用CheckBoxList

     < asp:CheckBoxList ID ="CheckBoxList1" runat ="server" >
     < asp:ListItem Text ="小明" Value ="A" > </asp:ListItem>
     < asp:ListItem Text ="小華" Value ="B" > </asp:ListItem>
     < asp:ListItem Text ="小張" Value ="C" > </asp:ListItem>
     < asp:ListItem Text ="小菜" Value ="D" > </asp:ListItem>
     </asp:CheckBoxList>

執行後,觀看程式碼
 

   < table id ="CheckBoxList1" border ="0" >
     < tr >
   < td > < input id ="CheckBoxList1_0" type ="checkbox" name ="CheckBoxList1$0" /> < label for ="CheckBoxList1_0" >小明 </label> </td>
     </tr> < tr >
   < td > < input id ="CheckBoxList1_1" type ="checkbox" name ="CheckBoxList1$1" /> < label for ="CheckBoxList1_1" >小華 </label> </td>
     </tr> < tr >
   < td > < input id ="CheckBoxList1_2" type ="checkbox" name ="CheckBoxList1$2" /> < label for ="CheckBoxList1_2" >小張 </label> </td>
     </tr> < tr >
   < td > < input id ="CheckBoxList1_3" type ="checkbox" name ="CheckBoxList1$3" /> < label for ="CheckBoxList1_3" >小菜 </label> </td>
     </tr>
</table>  

由上面的結果我們可以看到,input 裡並沒有Value的值可以讓JavaScript抓取,所以現在我們要幫他加一個attribute

 

     protected void Page_Load( object sender, EventArgs e)
     {
        foreach (ListItem li in CheckBoxList1.Items)
            li.Attributes["MainValue"] = li.Value;
        
    }

在觀看一次程式碼
 

< table id ="CheckBoxList1" border ="0" >
     < tr >
   < td > < span MainValue ="A" > < input id ="CheckBoxList1_0" type ="checkbox" name ="CheckBoxList1$0" /> < label for ="CheckBoxList1_0" >小明 </label> </span> </td>
     </tr> < tr >
   < td > < span MainValue ="B" > < input id ="CheckBoxList1_1" type ="checkbox" name ="CheckBoxList1$1" /> < label for ="CheckBoxList1_1" >小華 </label> </span> </td>
     </tr> < tr >
   < td > < span MainValue ="C" > < input id ="CheckBoxList1_2" type ="checkbox" name ="CheckBoxList1$2" /> < label for ="CheckBoxList1_2" >小張 </label> </span> </td>
     </tr> < tr >
   < td > < span MainValue ="D" > < input id ="CheckBoxList1_3" type ="checkbox" name ="CheckBoxList1$3" /> < label for ="CheckBoxList1_3" >小菜 </label> </span> </td>
     </tr>
</table>  

我們可以發現,input被Span包住了,而且裡面多了一個我們剛剛設定的MainValue Attribute,現在我們就可以引用Jquery來取值了

 

$( "#CheckBoxList1 input:checkbox").each( function(){

     $( this).parent('span').attr('MainValue');

});

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值