html 脚本复选框条件显示特定文本

问题描述 投票:0回答:1

您好,我需要代码方面的帮助,所以基本上我正在制作一个项目,当您选择复选框时,它将显示文本结果。我能够创建一个 if else 条件,但遇到问题,如果选中所有复选框,它会显示所有文本。 这是我的代码

<!DOCTYPE html>
<html>
<body>

<p>Display some text when the checkbox is checked:</p>

<label for="myCheck">Checkbox:</label> 
<input type="checkbox" id="myCheck" onclick="myFunction()">

<label for="myCheck">Checkbox2:</label> 
<input type="checkbox" id="myCheck1" onclick="myFunction()">

<p id="text" style="display:none"> both</p>
<p id="text2" style="display:none">ch1!</p>
<p id="text3" style="display:none">ch2!</p>

<script>
function myFunction() {
  var checkBox = document.getElementById("myCheck");
  
    /*should only show text "both"*/
  if (checkBox.checked == true && myCheck1.checked == true){
      text.style.display = "block";
    
  } else {
     text.style.display = "none";
     
  }
 /* show text "ch1"*/
   if (myCheck.checked == true){
  text2.style.display = "block";


     
  } else {
     text2.style.display = "none";
     
  }
  /* show text "ch2"*/
    if (myCheck1.checked == true){
    text3.style.display = "block";
    
  } else {
     text3.style.display = "none";
  }
}

</script>
</body>
</html>

我尝试通过这样的方式隐藏其他文本

if (checkBox.checked == true && myCheck1.checked == true){
      text.style.display = "block";
      text2.style.display = "none";
      text3.style.display = "none";


  } else {
     text.style.display = "none";

但它仍然不起作用,我真的需要帮助,谢谢。

javascript html if-statement checkbox
1个回答
0
投票

首先隐藏所有三个,然后根据需要启用它们。请参阅代码片段:

function myFunction() {
  var checkBox = document.getElementById("myCheck");

  text.style.display = "none";
  text2.style.display = "none";
  text3.style.display = "none";

  /*should only show text "both"*/
  if (checkBox.checked == true && myCheck1.checked == true){
    text.style.display = "block";
  }
  /* show text "ch1"*/
  else if (myCheck.checked == true){
    text2.style.display = "block";
  }
  /* show text "ch2"*/
  else if (myCheck1.checked == true){
    text3.style.display = "block";
  }
}
      <p>Display some text when the checkbox is checked:</p>

      <label for="myCheck">Checkbox:</label>
      <input type="checkbox" id="myCheck" onclick="myFunction()">

      <label for="myCheck">Checkbox2:</label>
      <input type="checkbox" id="myCheck1" onclick="myFunction()">

      <p id="text" style="display:none"> both</p>
      <p id="text2" style="display:none">ch1!</p>
      <p id="text3" style="display:none">ch2!</p>

© www.soinside.com 2019 - 2024. All rights reserved.