一、Jquery獲取選中的checkbox的值(多選)javascript
<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>
實現效果java
二、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>
實現的效果this