勾选复选框时显示两个div

时间:2016-09-26 11:34:16

标签: javascript jquery html

当我勾选复选框时,我有两个同一类的div,这两个div应该打开但只有一个div打开。尝试下面的脚本(在代码片段中)打开div。哪里不对了?请帮帮我。

function ShowHideDiv() {
  var chkYes = document.getElementById("chkYes");
  var pro = document.getElementsByClassName("pro")[0];
  pro.style.display = chkYes.checked ? "block" : "none";
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
  <input type="checkbox" id="chkYes" name="chkPassPort" onclick="ShowHideDiv()">Is Pro Contact</div>
<div class="pro" style="display: none">
  <div class="form-group">
    <input class="form-control" name="email" placeholder="Email">
  </div>
  <div class="form-group">
    <input type="file" name="userfile">
  </div>
  <div class="form-group">
    <textarea class="form-control" name="description" rows="3" placeholder="Description"></textarea>
  </div>
  <div class="form-group">
    <textarea class="form-control" rows="3" name="services" placeholder="Services"></textarea>
  </div>
</div>
<div class="pro" style="display:none;">
  <div class="form-group">
    <textarea class="form-control" rows="3" placeholder="सविस्तर माहिती"></textarea>
  </div>
  <div class="form-group">
    <textarea class="form-control" rows="3" placeholder="सुविधा"></textarea>
  </div>
</div>

2 个答案:

答案 0 :(得分:8)

中删除[0]
var pro = document.getElementsByClassName("pro")[0];

并添加for循环,因为[0]只会影响NodeList

中的第一个元素

&#13;
&#13;
function ShowHideDiv() {
  var chkYes = document.getElementById("chkYes");
  var pro = document.getElementsByClassName("pro");
  for (var i = pro.length - 1; i >= 0; i--) {
	pro[i].style.display = chkYes.checked ? "block" : "none";
  }
}
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="form-group">
  <input type="checkbox" id="chkYes" name="chkPassPort" onclick="ShowHideDiv()">Is Pro Contact</div>
<div class="pro" style="display: none">
  <div class="form-group">
    <input class="form-control" name="email" placeholder="Email">
  </div>
  <div class="form-group">
    <input type="file" name="userfile">
  </div>
  <div class="form-group">
    <textarea class="form-control" name="description" rows="3" placeholder="Description"></textarea>
  </div>
  <div class="form-group">
    <textarea class="form-control" rows="3" name="services" placeholder="Services"></textarea>
  </div>
</div>
<div class="pro" style="display:none;">
  <div class="form-group">
    <textarea class="form-control" rows="3" placeholder="सविस्तर माहिती"></textarea>
  </div>
  <div class="form-group">
    <textarea class="form-control" rows="3" placeholder="सुविधा"></textarea>
  </div>
</div>
&#13;
&#13;
&#13;

享受

答案 1 :(得分:0)

function ShowHideDiv() {
  var chkYes = document.getElementById("chkYes");
  for(var i = 0; i < document.getElementsByClassName("pro").length; i++){
      var pro = document.getElementsByClassName("pro")[i];
      pro.style.display = chkYes.checked ? "block" : "none";
  }
}