This article mainly introduces how to implement full selection, inverse selection, and assignment of checkBox in javascript, the implementation ideas and corresponding html and js code implementation processes are analyzed in detail in the form of instances. when we are working on projects, we often encounter the need to implement full selection of checkBox, there are also many examples on the internet about reverse selection and assignment. here I will share with you my frequently used methods and recommend them to you.
The code is as follows:
// Whether the js 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'); // add all IDs
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 );
}
})
// Add an id for one choice
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 all the code in this example, and it is helpful for you to learn how to use javascript to control checkbox.