I have a president/vice president checkbox
I wrote a script to uncheck appropriate vice president and all presidents after the user checks a president since only 1 president is allowed and a vice president can't be a president.
it is functioning good at the last president checkbox since the script i wrote especially else if(president[p].checked==false){
is enabling the checkboxes after it disables them. but i don't know why it is going inside the else statement.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
</head>
<body>
President <input type="checkbox" value="president"><br>
Vice President <input type="checkbox" value="vicePresident"><br><br>
President <input type="checkbox" value="president"><br>
Vice President <input type="checkbox" value="vicePresident"><br><br>
President <input type="checkbox" value="president"><br>
Vice President <input type="checkbox" value="vicePresident"><br><br>
President <input type="checkbox" value="president"><br>
Vice President <input type="checkbox" value="vicePresident"><br>
<script>
var president = document.querySelectorAll('input[type="checkbox"][value="president"]');
var vicePresident = document.querySelectorAll('input[type="checkbox"][value="vicePresident"]');
function change(){
var presidentChecked;
for (var p=0;p<president.length;p++){
if (president[p].checked==true){
presidentChecked=p;
vicePresident[p].disabled =true; // disable vice president of checked president
for (var p1 =0; p1<president.length;p1++){ // disable all unchecked presidents
if(p1 != p){
president[p1].disabled = true;
}
}
}
else if(president[p].checked==false){
vicePresident[p].disabled =false;
console.log("inside uncheck");
for(var uncheck =0; uncheck<president.length;uncheck++){
president[uncheck].disabled = false;
}
}
}
// else { //if (president[p].checked==false){
// //presidentChecked=p;
// vicePresident[p].disabled =false;
// for (var v =0; v<president.length;v++){
// president[v].disabled = false;
// }
// }
//}
// for (v = 0; v<vicePresident.length; v++){
// if (vicePresident[v].checked ==true){
// if(v != p){
// vicePresident[v].disabled = true;
// }
// }
// else if (vicePresident[p].checked == false){
// for (v = 0; v<vicePresident.length; v++){
// if(presidentChecked){
// vicePresident[v].disabled = true;
// } else { vicePresident[v].disabled =false; }
// }
// }
// }
}
for(var i = 0; i< president.length; i++){ // add an Event Listener to all the checkboxes
president[i].addEventListener('change', change);
vicePresident[i].addEventListener('change', change);
}
</script>
</body>
</html>
Aucun commentaire:
Enregistrer un commentaire