jquery 實現全選,反選,全不選等功能,下面直接以例子進行說明。設頁面有如下一組復選框和幾個相關按鈕(全選,反選,全不選等):
<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="獲得選中的所有值">
則分別實現相關功能的完整代碼如下:
$(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);
})
});
注意使用 jquery 之前必須要引入 jquery 包哦!
以上就是小編辛苦整理的代碼,是不是用起來很方便,希望能夠幫到大家。