开发者

Hiding columns in table JavaScript

This script stops working the moment I add a table inside a table, so how to get it worked? I don't need any jQuery solutions, I want pure JavaScript. Here's my script found on the Internet:

<script>

  function show_hide_column(col_no, do_show) {

    var stl;
    if (do_show) stl = 'block'
    else         stl = 'none';

    var tbl  = document.getElementById('id_of_table');
    var rows = tbl.getElementsByTagName('tr');

    for (var row=1; row<rows.length;row++) {
      var cels = rows[row].getElementsByTagName('td')
      cels[col_no].style.display=stl;
    }
  }

</script>

Here's my HTML:

<table id='id_of_table' border=1>
  <tr><td colspan="4"><table><tr><td></td></tr></table></td></tr>
  <tr><td>  2</td><td>   two</td><td>   deux</td><td>     zwei</td></tr>
  <tr><td>  3</td><td> three</td><td>  trois</td><td>     drei</td></tr>
  <tr><td>  4</td><td>  four</td><td>quattre</td><td>     vier</td></tr>
  <tr><td>  5</td><td>  five</td><td>   cinq</td><td>f&uuml;nf</td></tr>
  <tr><td>  6</td><td>   six</td><td>    six</td><td>    sechs</td></tr>
</table>

And here's my Form:

<form>
  Enter column no: <input开发者_如何学JAVA type='text' name=col_no><br>
  <input type='button' onClick='javascript:show_hide_column(col_no.value,  true);' value='show'>
  <input type='button' onClick='javascript:show_hide_column(col_no.value, false);' value='hide'>
</form>


You can leverage the col tag and then the solution is straightforward using only vanilla JavaScript. The col tag has only a few CSS attributes, but visibility is one of them:

function show_hide_column( col_no, do_show ){
   const table  = document.getElementById( 'id_of_table' )
   const column = table.getElementsByTagName( 'col' )[col_no]
   if ( column ){
      column.style.visibility = do_show?"":"collapse";
   }
}

const btnHide = document.getElementById( 'btnHide' )
btnHide.addEventListener( "click", () => show_hide_column( 2, false ))

const btnShow = document.getElementById( 'btnShow' )
btnShow.addEventListener( "click", () => show_hide_column( 2, true ))
 <table id='id_of_table' border=1>
      <col class="col1"/>
      <col class="col2"/>
      <col class="col3"/>
      <col class="col4"/>
      <tr><td colspan="4"><table><tr><td></td></tr></table></td></tr>
      <tr><td>  2</td><td>   two</td><td>   deux</td><td>     zwei</td></tr>
      <tr><td>  3</td><td> three</td><td>  trois</td><td>     drei</td></tr>
      <tr><td>  4</td><td>  four</td><td>quattre</td><td>     vier</td></tr>
      <tr><td>  5</td><td>  five</td><td>   cinq</td><td>fÜnf</td></tr>
      <tr><td>  6</td><td>   six</td><td>    six</td><td>    sechs</td></tr>
    </table>
    <button id="btnHide">hide French</button>
    <button id="btnShow">show French</button>

References:

  • col
  • visibility on quirksmode


You could use children and check their tagName to make sure they're td's. Something like this:

function show_hide_column(col_no, do_show) {
    var tbl = document.getElementById('id_of_table');
    var rows = tbl.getElementsByTagName('tr');

    for (var row = 0; row < rows.length; row++) {
        var cols = rows[row].children;
        if (col_no >= 0 && col_no < cols.length) {
            var cell = cols[col_no];
            if (cell.tagName == 'TD') cell.style.display = do_show ? 'block' : 'none';
        }
    }
}

Edit: Here's a working example: http://jsfiddle.net/3DjhL/2/.

Edit: In fact, I've just remembered the rows and cols properties, which make it even simpler. See http://jsfiddle.net/3DjhL/4/ to see it in action.

function show_hide_column(col_no, do_show) {
    var rows = document.getElementById('id_of_table').rows;

    for (var row = 0; row < rows.length; row++) {
        var cols = rows[row].cells;
        if (col_no >= 0 && col_no < cols.length) {
            cols[col_no].style.display = do_show ? '' : 'none';
        }
    }
}

Oh, and if you think the column numbers should start at 1 (which they don't), you'll have to offset that somewhere. For example at the top of show_hide_column():

col_no = col_no - 1;


The important thing here is the selector, it could be vanilla or jquery:

document.querySelectorAll('#yourtable tbody tr td:nth-child(1)').forEach(el=>el.style.display = 'none')

From the code above, the nth-child(1) selector has a 1-based index, there you define the column you want to hide ;)


I had a situation where it would have been a very big hassle to modify every single TD value and add the appropriate class name so I could toggle it. As a result I wrote some JavaScript to do that automatically. Please see the following code.

  tbl = document.getElementById("Mytable")
  classes = getClasses(tbl.rows[0]);
  setClasses(tbl, classes);
  toggleCol("col0");
  toggleCol("col1");



function getClasses(row){
    var cn = 0;
    var classes = new Array();
    for(x=0; x < row.cells.length; x++){
        var cell = row.cells[x];
        var c = new Column(cell.textContent.trim(), cell.offsetLeft, cell.offsetLeft + cell.offsetWidth, x);
        classes[x]= c;
    }
    return classes;
}

function Column(name, left, right, cols) {
    this.name = name;
    this.left = left;
    this.right = right;
    this.cols = cols;
}

function setClasses(table, classes){
    var rowSpans = new Array();
    for(x=0; x < table.rows.length; x++){
        var row = table.rows[x]; 
        for(y=0; y < row.cells.length; y++){
            var cell = row.cells[y];
            for(z=0; z < classes.length; z++){
              if(cell.offsetLeft >= classes[z].left && cell.offsetLeft <= classes[z].right){
                cell.className = "col" + classes[z].cols;
              }
            }
        }    
    }
}

function toggleCol(name){ 
  var cols = document.getElementsByClassName(name); 
  for(x=0; x < cols.length; x++){ 
    cols[x].style.display= (cols[x].style.display == 'none') ? '' : 'none'; 
   }
}

In my example I take a look at the first row to set the top level header (In my example I had several who had colspans). It uses the offsetLeft and offsetWidth to determine the range of the top header (which in my cases has sub headers), so that all sub-columns would toggle with its parent.

Based on these values setClasses sets the appropriate classes to all the elements.

In my example I then toggle "col0" and "col1", so they would be invisible (Running the function again would make them visible again).

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜