Jquery获取选中的checkbox的值

1、Jquery获取选中的checkbox的值(多选)

   <span><input name='cbServerType' type='checkbox' value='1'  />1111111</span>
   <span><input name='cbServerType' type='checkbox' value='2'  />2222222</span>
   <span><input name='cbServerType' type='checkbox' value='3'  />3333333</span>
   <span><input name='cbServerType' type='checkbox' value='4'  />4444444</span>
   <span><input name='cbServerType' type='checkbox' value='5' />5555555</span>

 

<script type="text/javascript">
        $(function () {

            $("input[name='cbServerType']:checkbox").click(function () {
                var type = '';
                $("input[name='cbServerType']:checkbox").each(function () {
                    if ($(this).attr("checked")) {
                        type += $(this).attr('value') + '|';
                    }
                });
                alert(type);
                $("#txtServerType").val(type);
            });
        }); 
    </script>

 

实现效果

2、Jquery从数据库读取值选中相应的checkbox(多选,以特定字符分割)

 

 <span><input name='cbServerType' type='checkbox' value='1'  />1111111</span>
<span><input name='cbServerType' type='checkbox' value='2'  />2222222</span>
<span><input name='cbServerType' type='checkbox' value='3'  />3333333</span>
<span><input name='cbServerType' type='checkbox' value='4'  />4444444</span>
<span><input name='cbServerType' type='checkbox' value='5' />5555555</span>
   
<input type="hidden" id="txtServerType" name="txtServerType" runat="server" value="1|2|3"  />

 

<script type="text/javascript">
        $(function () {
            var str = new String();
            var arr = new Array();
            str = $("#txtServerType").val();
            arr = str.split('|');
            for (var i = 0; i < arr.length; i++) {
                $("input[name='cbServerType'][value='" + arr[i] + "']").attr("checked", true);
            }
        }); 
    </script>

 

实现的效果

 

 

posted @ 2014-04-10 18:00  橙子819  阅读(22315)  评论(1编辑  收藏  举报