javascript 检查复选框是否在不使用 jquery 的情况下被选中?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27160604/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-28 07:03:02  来源:igfitidea点击:

check if a checkbox is checked without using jquery?

javascriptphp

提问by zeee9

I have form on page1.php:

我在 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 javascriptor XMLHttpRequest(). I tried doing it using javascript but it didn't work.

如果使用javascriptXMLHttpRequest()选中另一个复选框,我想禁用一个复选框。我尝试使用 javascript 来做,但没有用。

if(document.getElementById("f10").checked){
   document.getElementById("w20").disabled=true;
}

回答by Harrison Pickering

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

例如,您可以使用常规 javascript 来获取检查的 true 或 false 值,

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

  }
}

回答by Enzo Zapata

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

你能试试我的代码吗?它可以帮助你: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>

回答by ATechGuy

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

复选框的用途是用于多项选择,如果您只需要一项选择,请使用单选按钮

回答by Ellie

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/

您可以使用已检查的伪类,但如果这对您很重要,请注意缺少对 IE 8 的浏览器支持。 http://css-tricks.com/almanac/selectors/c/checked/