17

I have form on page1.php:

<form method="POST" action="page2.php">
<input type="checkbox" name="F10" id="f10">
<input type="checkbox" name="W10" id="w10">
<input type="checkbox" name="F20" id="f20">
<input type="checkbox" name="W20" id="w20">
<input type="checkbox" name="F30" id="f30">
<input type="checkbox" name="W30" id="w30">
</form>

I want to diable a checkbox if another checkbox is checked using javascript or XMLHttpRequest(). I tried doing it using javascript but it didn't work.

if(document.getElementById("f10").checked){
   document.getElementById("w20").disabled=true;
}
zeee9
  • 241
  • 1
  • 3
  • 11

4 Answers4

39

You can use regular javascript to get a true or false value for checked for example,

var isChecked= document.getElementById('elementName').checked;
if(isChecked){ //checked
  //execute code here
}else{ //unchecked
  //execute code here
}

or if you want whenever the checkbox check is changed

var checkbox = document.getElementById('elementName');
checkbox.addEventListener("change", functionname, false);

function functionname(){
  var isChecked = checkbox.checked;
  if(isChecked){ //checked

  }else{ //unchecked

  }
}
  • This may work, but would be better to determine the checked value from the incoming event, instead of calling the external selector. This way you can watch any element firing the event with a single check. It's possible by accessing `e.target.checked` in functionname (e is the event that must be passed to this function) – funder7 Jun 19 '21 at 21:22
1

can you try my code? it may help you :D

<form onclick="checkIfChecked()" method="POST" action="page2.php">

<input type="checkbox" name="F10" id="f10">F10
<input type="checkbox" name="W10" id="w10">W10
<input type="checkbox" name="F20" id="f20">F20
<input type="checkbox" name="W20" id="w20">W20
<input type="checkbox" name="F30" id="f30">F30
<input type="checkbox" name="W30" id="w30">W30
</form>

<script>
function checkIfChecked(){
    if(document.getElementById("f10").checked){
   document.getElementById("w20").disabled=true;
    } else {
  document.getElementById("w20").disabled=false;
   }
}
</script>
Enzo Zapata
  • 171
  • 1
  • 7
0

The purpose of a check box is for multiple selections, use radio buttons if you only want one selection available

ATechGuy
  • 1,240
  • 8
  • 13
  • No, I want multiple selections to be available . But I want one specific checkbox to be disabled if another is checked. – zeee9 Nov 26 '14 at 23:29
0

You can use the checked pseudo class but note lack of browser support for IE 8 if that matters to you. http://css-tricks.com/almanac/selectors/c/checked/

Ellie
  • 19
  • 1