When we are working on projects, we often encounter situations where we need to implement all selection, reverse selection and assignment of checkBox. There are many examples on the Internet. Here I share with you the methods I use, and I recommend them to you.
The code copy is as follows:
//JS value is in the array
Array.prototype.in_array = function(e){
for(i=0;i<this.length;i++){
if(this[i] == e)
return true;
}
return false;
}
//js array 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');//Select all to add 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");//Deselect to delete Ids
houseIds=[];
alert(houseIds);
}
})
//Single choice to add 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);
}
}
The above is the entire code of this example. I hope it will be helpful for everyone to learn to use javascript to control checkbox.