如何隐藏HTML表中的列

时间:2019-04-11 06:33:52

标签: javascript jquery html css

我有一个要从JSON数据呈现的HTML表,我有三行headers,第一行显示的是total,{{1 }}和Outlets,第二个显示金额类型,分别为jayanagarMalleshwaramKolarGross Amount,第三个显示金额栏明智的做法,然后显示完整数据的表主体

我想做的是:-

  • 我有一个带下拉菜单的输入字段,它是用于选择多个选项的复选框
  • 选择框是Discount,例如GSTNet AmountAmount TypeGross Amount,并且有一个按钮Discount
  • 因此,当用户在选择选项后单击GST时,我要尝试的是仅显示该列用户选择的内容

我的表格代码

Net Amount
Go

由于我的代码有点长,所以我在JavaScript代码中注释了我正在做什么的行,以使其更容易

我想根据用户选择隐藏列 这里的任何人都可以通过某种方法帮助我

3 个答案:

答案 0 :(得分:0)

执行此操作的适当方法是将列数据添加到表中,如下所示:

<table class="table table-striped table-bordered table-hover">
  <thead></thead>
  <colgroup>
    <col style="background-color:yellow; visibility: collapse;">
    <col id="total" span="4" style="background-color:red">
  </colgroup>
  <tbody>
    <tr>
      <th class="text-center">BillDate</th>
      <th colspan="4" class="text-center">Total</th>
      <th colspan="4" class="text-center">JAYANAGAR</th>
      <th colspan="4" class="text-center">MALLESHWARAM</th>
      <th colspan="4" class="text-center">KOLAR</th>
    </tr>
    ...
  </tbody>
</table>

但是有一个chrome bug可以防止可见性属性对cols或colgroups产生任何影响。

然后我将避免使用表,而是使用常规div手动构建表,并将列分组在一起。

答案 1 :(得分:0)

请通过这些链接。根据我的观点,您可以避免选择框(如果您仅将选择框值用于隐藏列)。您可以使用以下链接中提到的方法。

`https://codepen.io/feger/pen/eDybC`

show / hide table columns using jQuery

https://api.jquery.com/hide/#hide-options

您可以使用.hide()隐藏匹配的元素。

答案 2 :(得分:0)

我发现您在表头中使用了grossAmountdiscountgstnetAmount之类的类……这是一件好事。

如果将这些类添加到每一行的相应单元格中,甚至会更好。您可以使用真正简单的方法来显示/隐藏单元格。

我使用了3个嵌套循环来显示更复杂的,这些结果显示了基于具有选定类的标头的index来显示单元格。

我从#To输入中选取了选定的类,该输入是用逗号分隔的单词 close 列表,用于查找列索引。

请注意,它远非最佳和有效的编码方式,但是它可以工作……并且可能对您有启发性。 ;)

$("#save").on("click",function(){

  // Get the selected classes
  var classes = $("#To").val().replace(/\s+/g,"").split(",");

  // Hide cells
  $(".table thead tr:not(:first) th:not(:first-child)").hide();
  $(".table tbody tr td:not(:first-child)").hide();

  // Adjust thead first row colspans
  $(".table thead tr:first th:not(:first)").attr("colspan",classes.length);

  // For each classes selected
  for(i=0;i<classes.length;i++){
    //force 3 first letters to lowercase
    var classToShow = classes[i].substr(0,3).toLowerCase() + classes[i].substr(3);

    // For each element having the class
    $("."+classToShow).each(function(){
      var index = $(this).index();

      // Show selected cells in the thead
      $(".table thead tr:not(:first)").each(function(){
        $(this).find("th").eq(index).show();
      });

      // Show selected cells in the tbody
      $(".table tbody tr").each(function(){
        $(this).find("td").eq(index).show();
      });
    });
  }
});

$("#save").on("click",function(){
  
  // Get the selected classes
  var classes = $("#To").val().replace(/\s+/g,"").split(",");
  
  // Hide cells
  $(".table thead tr:not(:first) th:not(:first-child)").hide();
  $(".table tbody tr td:not(:first-child)").hide();
  
  // Adjust thead first row colspans
  $(".table thead tr:first th:not(:first)").attr("colspan",classes.length);
  
  // For each classes selected
  for(i=0;i<classes.length;i++){
    //force 3 first letters to lowercase
    var classToShow = classes[i].substr(0,3).toLowerCase() + classes[i].substr(3);
    
    // For each element having the class
    $("."+classToShow).each(function(){
      var index = $(this).index();
      
      // Show selected cells in the thead
      $(".table thead tr:not(:first)").each(function(){
        $(this).find("th").eq(index).show();
      });
      
      // Show selected cells in the tbody
      $(".table tbody tr").each(function(){
        $(this).find("td").eq(index).show();
      });
    });
  }
});

// ======================= NOTHING CHANGED BELOW

$(".checkbox-menu").on("change", "input[type='checkbox']", function() { // this one to select multiple options as check box
  $(this).closest("li").toggleClass("active", this.checked);
  var sList = "";
  $('input[type=checkbox]').each(function() {
    if (this.checked) {
      sList += $(this).val() + ","
    }
  });

  $("#To").val(sList.slice(0, -1));
});

$(document).on('click', '.allow-focus', function(e) {
  e.stopPropagation();
});

var data = [{
    "billdate": "2018-08-04",
    "outlet": "JAYANAGAR",
    "gross": 490465,
    "discount": 839,
    "GST": 28465,
    "amount": 518212
  },
  {
    "billdate": "2018-08-04",
    "outlet": "MALLESHWARAM",
    "gross": 99212,
    "discount": 0,
    "GST": 5567,
    "amount": 104801
  },
  {
    "billdate": "2018-08-04",
    "outlet": "KOLAR",
    "gross": 131349,
    "discount": 0,
    "GST": 6676,
    "amount": 138151
  },
  {
    "billdate": "2018-08-05",
    "outlet": "JAYANAGAR",
    "gross": 594466,
    "discount": 591,
    "GST": 34374,
    "amount": 628358
  },
  {
    "billdate": "2018-08-05",
    "outlet": "MALLESHWARAM",
    "gross": 109029,
    "discount": 0,
    "GST": 6062,
    "amount": 115113
  },
  {
    "billdate": "2018-08-05",
    "outlet": "KOLAR",
    "gross": 127449,
    "discount": 0,
    "GST": 6511,
    "amount": 134107
  },
  {
    "billdate": "2018-08-06",
    "outlet": "JAYANAGAR",
    "gross": 167811,
    "discount": 0,
    "GST": 9968,
    "amount": 177866
  },
  {
    "billdate": "2018-08-06",
    "outlet": "KOLAR",
    "gross": 62796,
    "discount": 0,
    "GST": 3257,
    "amount": 66095
  },
  {
    "billdate": "2018-08-07",
    "outlet": "JAYANAGAR",
    "gross": 267398,
    "discount": 268,
    "GST": 15898,
    "amount": 283124
  },
  {
    "billdate": "2018-08-07",
    "outlet": "MALLESHWARAM",
    "gross": 55381,
    "discount": 0,
    "GST": 3383,
    "amount": 58789
  },
  {
    "billdate": "2018-08-07",
    "outlet": "KOLAR",
    "gross": 64586,
    "discount": 6,
    "GST": 3285,
    "amount": 67886
  }
]

let formatData = function(data) {
  let billdates = [];
  let outlets = [];
  data.forEach(element => {
    if (billdates.indexOf(element.billdate) == -1) {
      billdates.push(element.billdate);
    }
    if (outlets.indexOf(element.outlet) == -1) {
      outlets.push(element.outlet);
    }
  });
  return {
    data: data,
    billdates: billdates,
    outlets: outlets,

  };
};

let renderTable = function(data) {
  billdates = data.billdates;
  outlets = data.outlets;
  data = data.data;
  let tbl = document.getElementById("dailySales");
  let table = document.createElement("table");
  let thead = document.createElement("thead");
  let headerRow = document.createElement("tr");
  let th = document.createElement("th");
  th.innerHTML = "BillDate";
  th.classList.add("text-center");
  headerRow.appendChild(th);
  let grandTotal = 0;
  let grandGross = 0;
  let grandDiscount = 0;
  let grandGst = 0;
  let outletWiseTotal = {};
  let outletWiseGross = {};
  let outletWiseDiscount = {};
  let outletWiseGst = {};
  th = document.createElement("th");
  th.colSpan = 4;
  th.innerHTML = "Total";
  th.classList.add("text-center");
  headerRow.appendChild(th);
  outlets.forEach(element => {

    th = document.createElement("th");
    th.colSpan = 4;
    th.innerHTML = element;
    th.classList.add("text-center");
    headerRow.appendChild(th);

    outletWiseTotal[element] = 0;
    outletWiseGross[element] = 0;
    outletWiseDiscount[element] = 0;
    outletWiseGst[element] = 0;
    data.forEach(el => {
      if (el.outlet == element) {
        outletWiseTotal[element] += parseInt(el.amount);
        outletWiseGross[element] += parseInt(el.gross);
        outletWiseDiscount[element] += parseInt(el.discount);
        outletWiseGst[element] += parseInt(el.GST);
      }
    });
    grandTotal += outletWiseTotal[element]; //calculating totals for Total column
    grandGross += outletWiseGross[element];
    grandDiscount += outletWiseDiscount[element];
    grandGst += outletWiseGst[element];
  });

  thead.appendChild(headerRow);
  headerRow = document.createElement("tr");
  th = document.createElement("th");
  th.innerHTML = "";
  headerRow.appendChild(th);

  for (i = 0; i < outlets.length + 1; i++) { //here i am making the header as col-span
    th = document.createElement("th");
    th.innerHTML = "Discount";
    th.classList.add("text-center");
    th.classList.add("discount"); //adding class to column discount
    headerRow.appendChild(th);

    th = document.createElement("th");
    th.innerHTML = "GST";
    th.classList.add("text-center");
    th.classList.add("gst"); //adding class to column gst
    headerRow.appendChild(th);

    th = document.createElement("th");
    th.innerHTML = "Net Amount";
    th.classList.add("text-center");
    th.classList.add("netAmount"); //adding class to column Net Amount
    headerRow.appendChild(th);

    th = document.createElement("th");
    th.innerHTML = "Gross Amount";
    th.classList.add("text-center");
    th.classList.add("grossAmount"); //adding class to column Gross Amount
    headerRow.appendChild(th);
  }

  headerRow.insertBefore(th, headerRow.children[1]);
  thead.appendChild(headerRow);
  table.appendChild(thead);

  headerRow = document.createElement("tr");
  td = document.createElement("th");
  td.innerHTML = "Total";
  td.classList.add("text-center");
  headerRow.appendChild(td);

  outlets.forEach(element => { // these are the table rows for each column
    td = document.createElement("th");
    td.innerHTML = outletWiseGross[element].toLocaleString('en-IN');
    td.classList.add("text-right");
    headerRow.appendChild(td);

    td = document.createElement("th");
    td.innerHTML = outletWiseDiscount[element].toLocaleString('en-IN');
    td.classList.add("text-right");
    headerRow.appendChild(td);

    td = document.createElement("th");
    td.innerHTML = outletWiseGst[element].toLocaleString('en-IN');
    td.classList.add("text-right");
    headerRow.appendChild(td);

    td = document.createElement("th");
    td.innerHTML = outletWiseTotal[element].toLocaleString('en-IN');
    td.classList.add("text-right");
    headerRow.appendChild(td);


  });
  td = document.createElement("th");
  td.innerHTML = grandTotal.toLocaleString('en-IN');
  td.classList.add("text-right");
  headerRow.insertBefore(td, headerRow.children[1]);

  td = document.createElement("th");
  td.innerHTML = grandGst.toLocaleString('en-IN');
  td.classList.add("text-right");
  headerRow.insertBefore(td, headerRow.children[1]);

  td = document.createElement("th");
  td.innerHTML = grandDiscount.toLocaleString('en-IN');
  td.classList.add("text-right");
  headerRow.insertBefore(td, headerRow.children[1]);

  td = document.createElement("th");
  td.innerHTML = grandGross.toLocaleString('en-IN');
  td.classList.add("text-right");
  headerRow.insertBefore(td, headerRow.children[1]);


  thead.appendChild(headerRow);
  table.appendChild(thead);

  let tbody = document.createElement("tbody");
  billdates.forEach(element => {
    let row = document.createElement("tr");
    td = document.createElement("td");
    td.innerHTML = element;
    row.appendChild(td);

    let total = 0;
    let totalGross = 0;
    let totalDiscount = 0;
    let totalGST = 0;
    outlets.forEach(outlet => {
      let ta = 0;
      let tg = 0;
      let tdi = 0;
      let tgst = 0;
      data.forEach(d => {
        if (d.billdate == element && d.outlet == outlet) {
          total += parseInt(d.amount);
          totalGross += parseInt(d.gross);
          totalDiscount += parseInt(d.discount);
          totalGST += parseInt(d.GST);
          ta = d.amount;
          tg = d.gross;
          tdi = d.discount;
          tgst = d.GST;
        }
      });

      td = document.createElement("td");
      td.innerHTML = tg.toLocaleString('en-IN');
      td.classList.add("text-right");
      row.appendChild(td);

      td = document.createElement("td");
      td.innerHTML = tdi.toLocaleString('en-IN');
      td.classList.add("text-right");
      row.appendChild(td);

      td = document.createElement("td");
      td.innerHTML = tgst.toLocaleString('en-IN');
      td.classList.add("text-right");
      row.appendChild(td);

      td = document.createElement("td");
      td.innerHTML = ta.toLocaleString('en-IN');
      td.classList.add("text-right");
      row.appendChild(td);




    });


    td = document.createElement("td");
    td.innerHTML = total.toLocaleString('en-IN');
    td.classList.add("text-right");
    row.insertBefore(td, row.children[1]);

    td = document.createElement("td");
    td.innerHTML = totalGST.toLocaleString('en-IN');
    td.classList.add("text-right");
    row.insertBefore(td, row.children[1]);

    td = document.createElement("td");
    td.innerHTML = totalDiscount.toLocaleString('en-IN');
    td.classList.add("text-right");
    row.insertBefore(td, row.children[1]);



    td = document.createElement("td");
    td.innerHTML = totalGross.toLocaleString('en-IN');
    td.classList.add("text-right");
    row.insertBefore(td, row.children[1]);


    tbody.appendChild(row);
  });

  table.appendChild(tbody);
  tbl.innerHTML = "";
  tbl.appendChild(table);
  table.classList.add("table");
  table.classList.add("table-striped");
  table.classList.add("table-bordered");
  table.classList.add("table-hover");
}
let formatedData = formatData(data);
renderTable(formatedData);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/js/bootstrap.min.js"></script>

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css">
<div class="form-group  col-xs-12 col-sm-12 col-md-4 col-lg-4">
  <label for="subCategoryCode">Filter Data :</label>
  <div class="input-group">
    <input type="text" class="form-control" aria-label="Text input with dropdown button" name="To" id="To" readonly>
    <div class="input-group-append">
      <button class="btn btn-outline-secondary dropdown-toggle" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"></button>
      <ul class="dropdown-menu checkbox-menu allow-focus" aria-labelledby="dropdownMenu1">

        <li><label> <input type="checkbox"
							value="Gross Amount"> Gross Amount
					</label></li>

        <li><label> <input type="checkbox"
							value="Discount"> Discount
					</label></li>

        <li><label> <input type="checkbox"
							value="GST"> GST
					</label></li>
        <li><label> <input type="checkbox"
							value="Net Amount"> Net Amount	
					</label></li>


      </ul>
    </div>
    <button type="button" class="commonButton" id="save">
						<i class="fa fa-search"></i>&nbsp;Go
					</button>
  </div>

</div>


<div align="left" class="table table-responsive" id="commonDvScroll">
  <table id="dailySales" class="maxWidthCommonTable"></table>
</div>


编辑

这是一个有关如何使用单元格类显示/隐藏列的示例。我在您的表的简化版本上完成了此操作...

顺便说一句,这里的表是否是“动态的”不是问题。...由于show / hide操作是在呈现表时运行的。因此,所有需要的元素都存在,并且可以针对用户触发的事件。

我使用了您拥有的4列类……还有2个类:selectable定位可能隐藏/显示的所有单元格,colspaned定位需要colspan属性的标题调整。

因此,正如您在下面看到的那样,它效率更高,因为只有一个简单的循环来收集每个4个复选框的值和相应的类。我已经将这些类放在了data属性中。

var selections = $(".checkbox-menu :checkbox");
var filterData = $("#To");
var originalColspan = $(".colspaned").attr("colspan");

selections.on("change",function(){
  
  // Clear the "Filter Data" input
  filterData.val("");
  
  // Get the selected classe
  var classes = [];
  var values = [];
  selections.each(function(){
    if($(this).is(":checked")){
      
      // Get the selected classe
      classes.push( "." + $(this).data("select") );
      
      // Value in the "filter Data" input
      values.push( $(this).val() );
    }
  });
  
  // Value in the "filter Data" input... If still useful (!)
  filterData.val(values.join(","));
  
  // Get how many selected
  var selectedAmount = classes.length;
  
  // If at least one selection
  if(selectedAmount>0){
  
    // Adjust headers colspan attr
    $(".colspaned").attr("colspan",selectedAmount);
    
    // Hide all cells
    $(".selectable").hide();
    
    // Show selected
    $(classes.join(",")).show();
  }
  
  // If no selection, show all cells
  else{
    $(".selectable").show();
    
    // Adjust headers colspan attr
    $(".colspaned").attr("colspan",originalColspan);
  }
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/js/bootstrap.min.js"></script>

<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.2/css/bootstrap.min.css">

<div class="form-group  col-xs-12 col-sm-12 col-md-4 col-lg-4">
  <label for="subCategoryCode">Filter Data :</label>
  <div class="input-group">
    <input type="text" class="form-control" aria-label="Text input with dropdown button" name="To" id="To" readonly>
    <div class="input-group-append">
      <button class="btn btn-outline-secondary dropdown-toggle" type="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"></button>
      <ul class="dropdown-menu checkbox-menu allow-focus" aria-labelledby="dropdownMenu1">

        <li>
          <label>
            <input type="checkbox" value="Gross Amount" data-select="grossAmount"> Gross Amount
          </label>
        </li>

        <li>
          <label>
            <input type="checkbox" value="Discount" data-select="discount"> Discount
          </label>
        </li>

        <li>
          <label>
            <input type="checkbox" value="GST" data-select="gst"> GST
          </label>
        </li>
        
        <li>
          <label>
            <input type="checkbox" value="Net Amount" data-select="netAmount"> Net Amount  
          </label>
        </li>


      </ul>
    </div>
    <button type="button" class="commonButton" id="save">
      <i class="fa fa-search"></i>&nbsp;Go
    </button>
  </div>

</div>


<div align="left" class="table table-responsive" id="commonDvScroll">
  <table id="dailySales" class="maxWidthCommonTable">
    <table id="dailySales" class="maxWidthCommonTable"><table class="table table-striped table-bordered table-hover">
      <thead>
        <tr>
          <th class="text-center">BillDate</th>
          <th colspan="4" class="text-center colspaned">Total</th>
          
        </tr>
        <tr>
          <th>
          </th>
          <th class="text-center grossAmount selectable">Gross Amount</th>
          <th class="text-center discount selectable">Discount</th>
          <th class="text-center gst selectable">GST</th>
          <th class="text-center netAmount selectable">Net Amount</th>
          
        </tr>
        <tr>
          <th class="text-center">Total</th>
          <th class="text-right grossAmount selectable">21,69,942</th>
          <th class="text-right discount selectable">1,704</th>
          <th class="text-right gst selectable">1,23,446</th>
          <th class="text-right netAmount selectable">22,92,502</th>
          
        </tr>
      </thead>
      <tbody>
        <tr>
        <td>2018-08-04</td>
        <td class="text-right grossAmount selectable">7,21,026</td>
        <td class="text-right discount selectable">839</td>
        <td class="text-right gst selectable">40,708</td>
        <td class="text-right netAmount selectable">7,61,164</td>
        
        </tr>
        <tr>
        <td>2018-08-05</td>
        <td class="text-right grossAmount selectable">8,30,944</td>
        <td class="text-right discount selectable">591</td>
        <td class="text-right gst selectable">46,947</td>
        <td class="text-right netAmount selectable">8,77,578</td>
        
        </tr>
        <tr>
        <td>2018-08-06</td>
          <td class="text-right grossAmount selectable">2,30,607</td>
          <td class="text-right discount selectable">0</td>
          <td class="text-right gst selectable">13,225</td>
          <td class="text-right netAmount selectable">2,43,961</td>
          
        </tr>
        <tr>
          <td>2018-08-07</td>
          <td class="text-right grossAmount selectable">3,87,365</td>
          <td class="text-right discount selectable">274</td>
          <td class="text-right gst selectable">22,566</td>
          <td class="text-right netAmount selectable">4,09,799</td>
          
        </tr>
      </tbody>
    </table>
  </table>
</div>