Home > Web Front-end > JS Tutorial > Implement functions such as selecting all check boxes, inverting selections, and deselecting none based on jquery_jquery

Implement functions such as selecting all check boxes, inverting selections, and deselecting none based on jquery_jquery

WBOY
Release: 2016-05-16 15:36:26
Original
1273 people have browsed it

jquery implements functions such as selecting all, inverting selection, and deselecting all. The following is an example. Assume that the page has the following set of check boxes and several related buttons (select all, invert selection, unselect all, etc.):

<input type="checkbox" name="fruit" value="apple" />苹果 
<input type="checkbox" name="fruit" value="orange" />橘子 
<input type="checkbox" name="fruit" value="banana" />香蕉 
<input type="checkbox" name="fruit" value="grape" />葡萄 
 
<input type="button" id="btn1" value="全选"> 
<input type="button" id="btn2" value="全不选"> 
<input type="button" id="btn3" value="反选"> 
<input type="button" id="btn4" value="选中所有奇数"> 
<input type="button" id="btn5" value="获得选中的所有值"> 
Copy after login

The complete code to implement the relevant functions respectively is as follows:

$(function(){ 
  $('#btn1').click(function(){//全选 
    $("[name='fruit']").attr('checked','true'); 
  }); 
  $('#btn2').click(function(){//全不选 
    $("[name='fruit']").removeAttr('checked'); 
  }); 
  $('#btn3').click(function(){//反选 
    $("[name='fruit']").each(function(){ 
      if($(this).attr('checked')){ 
        $(this).removeAttr('checked'); 
      }else{ 
        $(this).attr('checked','true'); 
      } 
    }) 
  }); 
  $("#btn4").click(function(){//选中所有奇数 
    $("[name='fruit']:even").attr('checked','true'); 
  }) 
  $("#btn5").click(function(){//获取所有选中的选项的值 
    var checkVal=''; 
    $("[name='fruit'][checked]").each(function(){ 
      checkVal+=$(this).val()+','; 
    }) 
    alert(checkVal); 
  }) 
}); 
Copy after login

Note that you must import the jquery package before using jquery!

The above is the code that the editor has worked hard to compile. Is it very convenient to use? I hope it can help everyone.

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