Hide datagrid column with javascript?

I have a .net datagrid with approximately 20 columns. I need a visibilty column that needs to be switched based on a button click using javascript. Any ideas?

+5
source share
5 answers

You want to use COLGROUP for this, otherwise you need to apply a style to each cell in each row, which will be terribly inefficient and most likely will hang the browser, especially if your grid is large. All of the above answers that rely on a third-party library (jQuery) do this in a slow / lazy way. Since all Javascript is client-side, you probably want to pay a little more attention when it comes to efficiency.

Here you go ...

function hideColumns(tableId, colIndexArray) {
  var tbl = document.getElementById(tableId);
  if(!tbl) return;

  var rows = tbl.getElementsByTagName("TBODY");

  if(rows.length == 0)
    rows = tbl.getElementsByTagName("TR");
  else
    rows = rows[0].getElementsByTagName("TR");

  var cols = rows[rows.length - 1].getElementsByTagName("TD");
  var colgroup = document.createElement("COLGROUP");

  for(var i = 0, l = cols.length; i < l; i++) {
    var col = document.createElement("COL");

    for(var num in colIndexArray) {
      if(colIndexArray[num] == i) {
        if(document.all)
          col.style.display = 'none'
        else
          col.style.visibility = 'collapse';

        break;
      }
    }

    colgroup.appendChild(col);
  }

  tbl.insertBefore(colgroup, tbl.childNodes[0]);
}

Use it like this:

var columnsToHide = [0, 1, 2]; // hide the first 3 columns
var tableId = "tableIdHere"; // view the source of your page to get this
hideColumns(tableId, columnsToHide);

Tested in IE7 and FF3: Hide Table Columns with Javascript

+5
source

Use jQuery ! This is amazing.

Your link might look like this:

<a href="javascript:ToggleColumn();">Toggle My Column</a>

Your javascript function might look like this:

function ToggleColumn()
{
    $(".myColumn").toggle();
}

class= "myColumn", javascript . <ItemStyle /> DataGrid, :

<asp:TemplateColumn runat="server">
    <ItemStyle CssClass="myColumn" />
</asp:TemplateColumn>

, , jQuery -, :

<script src="/jquery-1.3.2.min.js" type="text/javascript" charset="utf-8"></script>

jQuery .

0

- JQuery.

"hidden: true". JS.

-1

jquery, ... , - , . 3.

$('table.tableCSS tr').find('td:eq(2)').hide(); // eq(index)
-1
source

All Articles