jQuery操作checkbox选择

xiaoxiao2021-02-27  166

attr 更加jQuery版本 缓存prop

1. 判断checkbox(复选框)是否被选中 

很多朋友判断  if($("#id").attr("checked")=="true") 这个是错误的,其实应该是 if($("#id").attr("checked")==true)

if($("#id").is(":checked")== true)

2. 全选

  $("[name = chkItem]:checkbox").attr("checked", true);

3、全不选

$("[name = chkItem]:checkbox").attr("checked", false);

 

$("[name = chkItem]:checkbox").each(function () {                      $(this).attr("checked", !$(this).attr("checked"));                  });

5.选中所有奇数

 $("[name='checkbox']:even").attr("checked",'true');

6.获得选中的所有值

$("[name='checkbox'][checked]").each(function(){      str+=$(this).val()+""r"n";     })

7、获取单个checkbox选中项(三种写法)

$("input:checkbox:checked").val() 或者 $("input:[type='checkbox']:checked").val(); 或者 $("input:[name='ck']:checked").val();

8.获取多个checkbox选中项

$('input:checkbox').each(function() {         if ($(this).attr('checked') ==true) {                 alert($(this).val());         } });

9.设置第一个checkbox 为选中值

$('input:checkbox:first').attr("checked",'checked');

或者 $('input:checkbox').eq(0).attr("checked",'true');

10.根据索引值设置任意一个checkbox为选中值

$('input:checkbox).eq(索引值).attr('checked', 'true');索引值=0,1,2.... 或者 $('input:radio').slice(1,2).attr('checked', 'true');

11、选中多个checkbox同时选中第1个和第2个的checkbox $('input:radio').slice(0,2).attr('checked','true');

12、根据Value值设置checkbox为选中值 $("input:checkbox[value='1']").attr('checked','true');

转载请注明原文地址: https://www.6miu.com/read-15787.html

最新回复(0)