這篇文章主要介紹了javascript實(shí)現(xiàn)checkBox的全選,反選與賦值的方法,以實(shí)例形式詳細(xì)分析了實(shí)現(xiàn)的思路及對應(yīng)的html與js代碼的實(shí)現(xiàn)過程
我們平時(shí)在做項(xiàng)目的時(shí)候,經(jīng)常會遇到需要實(shí)現(xiàn)實(shí)現(xiàn)checkBox的全選,反選與賦值的情況,網(wǎng)上也有許多的范例,這里給大家分享的是本人常用的方法,推薦給大家。
復(fù)制代碼代碼如下:
//js 數(shù)值是否在數(shù)組中
Array.prototype.in_array = function(e){
for(i=0;i<this.length;i++){
if(this[i] == e)
return true;
}
return false;
}
//js數(shù)組index
Array.prototype.find_str=function(string){
var str = this.join("");
return str.indexOf(string);
}
var houseIds=new Array();
$("#chebox-list-all").click(function(){
if($("#chebox-list-all").attr("checked")){
$("[name='checkboxes']").attr("checked",'true');//全選 增加id
var ids = document.getElementsByName('checkboxes');
var value = new Array();
for(var i = 0; i < ids.length; i++){
if(ids[i].checked)
houseIds.push(ids[i].value);
}
alert(houseIds);
}else{
$("[name='checkboxes']").removeAttr("checked");//反選 刪除Ids
houseIds=[];
alert(houseIds);
}
})
//單選增加id
function check(obj){
if(!houseIds.in_array(obj.value)){
houseIds.push(obj.value);
alert(houseIds);
}else{
var index=houseIds.find_str(obj.value);
houseIds.splice(index, 1)
alert(houseIds);
}
}
以上就是本示例的全部代碼了,希望對大家學(xué)習(xí)使用javascript控制checkbox有所幫助。