javascript implements the full selection unselection and assignment of checkBox

  • 2020-05-12 02:13:27
  • OfStack

When we are doing projects at ordinary times, we often encounter situations in which we need to realize the full selection, inverse selection and assignment of checkBox. There are also many examples on the Internet. Here I share with you my common methods and recommend them to you.


//js Whether the 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 An array of 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');// Future generations increase 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");// The selected delete Ids
    houseIds=[];
    alert(houseIds);
  }
})
// Radio increase 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);
  }
}

That's all the code for this example, and I hope it will help you learn how to control checkbox using javascript.


Related articles: