Home  >  Article  >  Web Front-end  >  Javascript implements full selection, inverse selection and assignment of checkBox_javascript skills

Javascript implements full selection, inverse selection and assignment of checkBox_javascript skills

WBOY
WBOYOriginal
2016-05-16 16:10:141121browse

When we usually work on projects, we often encounter situations where we need to realize the full selection, inverse selection and assignment of checkBox. There are many examples on the Internet. Here I will share with you my commonly used method and recommend it to everyone.

Copy code The code is as follows:

//js whether the value is in the array
Array.prototype.in_array = function(e){
​for(i=0;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 and 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");//Reverse selection Delete Ids
  houseIds=[];
alert(houseIds);
}
})
//Add id to single selection
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 the checkbox.

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn