How can I edit the following script so that I can get the td appear under the corresponding th, not every td under the first th? Want to hide/show contents of tr based on th clicked

 function toggleColumn(n) {
    var currentClass = document.getElementById("mytable").className;
    if (currentClass.indexOf("show" + n) != -1) {
      document.getElementById("mytable").className = currentClass.replace("show" + n, "");
    } else {
      document.getElementById("mytable").className += " " + "show" + n;
    }
  }

Example: https://jsfiddle.net/Oliver250/jgtrxuqd/4/

1 Answers

0
Aishwarya On Best Solutions

Using Jquery---------------->

$("th").on("click",function(){

  var indexVal = $(this).index()
    var cls = $("td:eq(" + indexVal + ")>div").attr("class")
    if (cls != ""){
      $("td:eq(" + indexVal + ")>div").removeClass(cls);
    }else{
      $("td:eq(" + indexVal + ")>div").addClass("col");
      }
})
table,
th,
td {
  border: 2px solid black;
  border-collapse: collapse;
  margin-top: 10px;
  padding: 10px;
}

th,
td {
  text-align: left;
}

.col {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table align="center" id="mytable">

  <tr>
    <th>TH1</th>
    <th >TH2</th>
    <th>TH3</th>
  </tr>
  <tr>
    <td>
    <div  class="col">
     TH1:TD1 : <input type="text"><br> TH1:TD1 : <input type="text"><br> TH1:TD1 : <input type="text">

    </div > 
    </td>

    <td >  <div  class="col">
      TH2:TD2 : <input type="text"><br> TH2:TD2 : <input type="text">
      </div> </td>

    <td >  <div  class="col">
      TH3:TD3 : <input type="text"><br> TH3:TD3 : <input type="text">
      </div>  </td>
  </tr>
</table>

Using javascript ---------------->

table,
th,
td {
  border: 2px solid black;
  border-collapse: collapse;
  margin-top: 10px;
  padding: 10px;
}

th,
td {
  text-align: left;
}

.col {
  display: none;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table align="center" id="mytable">

  <tr>
    <th onclick="toggleColumn(1)">TH1</th>
    <th onclick="toggleColumn(2)">TH2</th>
    <th onclick="toggleColumn(3)">TH3</th>
  </tr>
  <tr>
    <td>
    <div  class="col">
     TH1:TD1 : <input type="text"><br> TH1:TD1 : <input type="text"><br> TH1:TD1 : <input type="text">

    </div > 
    </td>

    <td >  <div  class="col">
      TH2:TD2 : <input type="text"><br> TH2:TD2 : <input type="text">
      </div> </td>

    <td >  <div  class="col">
      TH3:TD3 : <input type="text"><br> TH3:TD3 : <input type="text">
      </div>  </td>
  </tr>
</table>
<script>
  function toggleColumn(inputChk) {
    var indexVal = (inputChk) - Number(1)
    var cls = $("td:eq(" + indexVal + ")>div").attr("class")
    if (cls != ""){
      $("td:eq(" + indexVal + ")>div").removeClass(cls);
    }else{
      $("td:eq(" + indexVal + ")>div").addClass("col");
      }}
</script>