Home > Web Front-end > JS Tutorial > body text

jquery controls checkbox selection, inverse selection or no selection with one click

小云云
Release: 2018-01-15 17:01:51
Original
1467 people have browsed it

This article mainly introduces in detail the jquery one-click control of checkbox selection, inverse selection or no selection. It has certain reference value. Interested friends can refer to it. I hope it can help everyone.

The jquery attr() method may cause problems in obtaining the checked value of the tag, so the prop() method is used.

Hml's checkbox does not add a name, only p nesting is used.

If there is a better way, please give me some advice!!


//全选
$('#allChecked').change(function(){
   $('#box').children(':checkbox').prop('checked',$(this).is(':checked')?true:false);
});
Copy after login


//反选
$('#invertChecked').change(function(){
 if($(this).is(':checked')){
   $('#box').children(':checkbox').each(function(){
    $(this).prop('checked',$(this).is(':checked')?false:true);
   });
 }
});
Copy after login


//一键控制全选、反选、全不选
$('#orChecked').change(function(){
 if($(this).is(':checked')){
   var box = $('#box').children(':checkbox');
   if(box.length==box.filter(':not(:checked)').length){  // 复选框长度和没选中的个数一样 -> 全选 , .not(':checked').length 也可以。
   $('#box').children(':checkbox').prop('checked',true);
 }else{   // 如果有选中个数,-> 反选 
   $('#box').children(':checkbox').each(function(){   
    $(this).prop('checked',$(this).is(':checked')?false:true);
   });
 }else{
   $('#box').children(':checkbox').prop('checked',false);  // 如控制键取消选中,剩余的checkbox也取消选中
 }
  
});
Copy after login


 <p align="center">
     
   <p id="box">
     <input type="checkbox" value="1">西瓜
     <input type="checkbox" value="2">芒果
     <input type="checkbox" value="3">橙
     <input type="checkbox" value="4">山竹
     <input type="checkbox" value="5">草莓
     <input type="checkbox" value="6">火龙果
   </p>  
       
   <br>
       
   <input type="checkbox" id="allChecked">全选
   <input type="checkbox" id="invertChecked">反选
   <input type="checkbox" id="orChecked">全选/反选/全不选
       
 </p>
Copy after login

Related recommendations:

##JQuery-based checkbox selection problem analysis

Checkbox selection and inverse/cancel selection

###

The above is the detailed content of jquery controls checkbox selection, inverse selection or no selection with one click. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!