Sagar Kodte Sagar Kodte - 2 months ago 7
Javascript Question

show two divs when tick the checkbox

I have two divs with same class when i tick the checkbox these two divs should be open but only one div is opening. tried below script (in snippet) to open divs. Anything wrong? please help me.



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>




Answer

Remove [0] from

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

and add for loop as [0] will affect only first element from NodeList

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";
  }
}
<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>

Enjoy