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="获得选中的所有值">
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); }) });
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.