Home > Article > Web Front-end > Implement functions such as selecting all check boxes, inverting selections, and deselecting all check boxes based on jquery
jquery implements functions such as selecting all, inverting selection, and not selecting all. The following is an example. Assume that the page has the following set of check boxes and several related buttons (select all, inverse select, 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="获得选中的所有值">
then implement related functions respectively. The complete code 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); }) });
Note that the jquery package must be introduced 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.
For more related articles on how to implement checkbox selection, inverse selection, and deselecting all based on jquery, please pay attention to the PHP Chinese website!