根据复选框状态在JavaScript中添加/删除表列

时间:2019-01-02 22:40:41

标签: javascript html

在以下演示中,如果将列表粘贴到搜索框中:

00001,00002,00003,00004,00005,00006,00007,00008,00009,00010,00011,00012,00013

它将从位于以下位置的JSON文件中提取相应的属性功能: https://api.myjson.com/bins/f2nos

var data = {};

$(document).ready(function () {
    $("#Search").click(function (any) {
		$("tbody").empty();
        var searchIds = new Set($('#searchBox').val().split(/[ ,\r\n]+/).map(s => s.trim()));
        searchIds.forEach(CODE =>
			
            $("tbody").append('<tr>' + `<td class="theader1" id="theader1">${CODE}</td>` + `<td class="theader2" id="theader2">${datab[CODE]}</td>` + `<td class="theader3" id="theader3">${datac[CODE]}</td>` + `<td class="theader4" id="theader4">${datad[CODE]}</td>` + '</tr>'));
    });
});

function getdata() {
    fetch("https://api.myjson.com/bins/f2nos").then(resp => resp.json()).then(resp => {
        datab = Object.assign({}, ...resp.features.map(
            ({ properties: { CODE, DIVISION}}) => ({ [CODE]: DIVISION}))
        );
        datac = Object.assign({}, ...resp.features.map(
            ({ properties: { CODE, PROVINCE}}) => ({ [CODE]: PROVINCE}))
        );
        datad = Object.assign({}, ...resp.features.map(
            ({ properties: { CODE, NAME}}) => ({ [CODE]: NAME}))
        );		
    });
}

getdata();						
	
/*Checkbox To Table Head*/
$("input:checkbox:not(:checked)").each(function() {
    var column = "table ." + $(this).attr("name");
    $(column).hide();
});

$("input:checkbox").click(function(){
    var column = "table ." + $(this).attr("name");
    $(column).toggle();
});
  <head>
   <title>Code Table</title>
	<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
	<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
  </head>
  <body>
	<span class="clearable">
		<input id="searchBox" type="text" rows="25" cols="15" WRAP="HARD" placeholder="Paste the list HERE" type="search">
	</span>
	<button class="button button1" id="Search">Search</button>	
	</br>
	<p><input type="checkbox" class="theader1" name="theader1" checked="checked"> CODE
  <input type="checkbox" class="theader2" name="theader2" checked="checked"> DIVISION
  <input type="checkbox" class="theader3" name="theader3" checked="checked"> PROVINCE
  <input type="checkbox" class="theader4" name="theader4" checked="checked"> NAME</p>
	</br>
		<table border="1px" id="data">
			<thead>
			<tr>
			<th class="theader1" id="theader1">CODE</th>
			<th class="theader2" id="theader2">DIVISION</th>
			<th class="theader3" id="theader3">PROVINCE</th>	
			<th class="theader4" id="theader4">NAME</th>
			</tr>
			</thead>
			<tbody></tbody>
		</table>

复选框控制表格列是否可见。

因此,如果您取消选中“代码”复选框,则“代码”列将消失

一个小问题。

当我在搜索之前取消选中任何复选框(例如CODE),然后搜索时,得到以下奇怪的表: enter image description here

发生这种情况的原因是,即使未选中该复选框,APPEND()语句仍会附加CODE列。

那么如何将复选框状态连接到append语句,以使即使在搜索后也不会显示列?

我假设解决方案是将每个Table TD变成一个变量,并以某种方式将其连接到复选框的状态?

如何实现?还是更好的解决方案?

2 个答案:

答案 0 :(得分:1)

  

“那么如何将复选框状态连接到append语句,以便即使在搜索后也不会显示列?”

     

“我假设解决方案是将每个表TD转换为变量,并以某种方式将其连接到复选框的状态?”

     

“如何实现?还是更好的解决方案?”

您是正确的,这是将行添加到表中而不检查是否未选中任何复选框的方式。以下是所做的更改:

  • 所有复选框仅具有一个类:.theader

  • 所有<td>都删除了#id,这是无效的HTML,重复了#id,而且毫无用处。

  • 以下是有关列生成的问题的解决方案:

   searchIds.forEach(CODE => {
     // Row template stored as an array of strings 
     var theader = [
       `<td class="theader1">${CODE}</td>`, 
       `<td class="theader2">${datab[CODE]}</td>`,
       `<td class="theader3">${datac[CODE]}</td>`, 
       `<td class="theader4">${datad[CODE]}</td>`
     ];
     // <tr> is appended before <td> is generated 
     $("tbody").append('<tr></tr>');
     // Each checkbox...
     $('.theader').each(function(idx) {
        // ...that is checked... 
        if ($(this).is(':checked')) {
          // ...will append the string from the array according to current index
          $("tbody tr:last").append(`${theader[idx]}`);
        }
     });
  });

var datab, datac, datad;
$("#Search").click(function() {
  $("tbody").empty();

  var searchIds = new Set($('#searchBox').val().split(/[ ,\r\n]+/).map(s => s.trim()));

  searchIds.forEach(CODE => {

    var theader = [`<td class="theader1">${CODE}</td>`, `<td class="theader2">${datab[CODE]}</td>`, `<td class="theader3" >${datac[CODE]}</td>`, `<td class="theader4">${datad[CODE]}</td>`];
    $("tbody").append('<tr></tr>');
    $('.theader').each(function(idx) {

      if ($(this).is(':checked')) {
        $("tbody tr:last").append(`${theader[idx]}`);
      }
    });
  });
});


function getdata() {
  fetch("https://api.myjson.com/bins/f2nos").then(resp => resp.json()).then(resp => {
    datab = Object.assign({}, ...resp.features.map(
      ({
        properties: {
          CODE,
          DIVISION
        }
      }) => ({
        [CODE]: DIVISION
      })));
    datac = Object.assign({}, ...resp.features.map(
      ({
        properties: {
          CODE,
          PROVINCE
        }
      }) => ({
        [CODE]: PROVINCE
      })));
    datad = Object.assign({}, ...resp.features.map(
      ({
        properties: {
          CODE,
          NAME
        }
      }) => ({
        [CODE]: NAME
      })));
  });
}

getdata();

/*Checkbox To Table Head*/
$(".theader:not(:checked)").each(function() {
  var column = "table ." + $(this).attr("name");
  $(column).hide();
});

$(".theader").click(function() {
  var column = "table ." + $(this).attr("name");
  $(column).toggle();
});
<head>
  <title>Code Table</title>

  <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
</head>

<body>
  <fieldset>
    <input id="searchBox" placeholder="Paste the list HERE" type="search">

    <button type="button" id="Search">Search</button>
    <br><br>
    <input type="checkbox" class="theader" name="theader1" checked="checked"> CODE
    <input type="checkbox" class="theader" name="theader2" checked="checked"> DIVISION
    <input type="checkbox" class="theader" name="theader3" checked="checked"> PROVINCE
    <input type="checkbox" class="theader" name="theader4" checked="checked"> NAME

  </fieldset>
  <br>
  <table border="1px" id="data">
    <thead>
      <tr>
        <th id="theader1" class="theader1">CODE</th>
        <th id="theader2" class="theader2">DIVISION</th>
        <th id="theader3" class="theader3">PROVINCE</th>
        <th id="theader4" class="theader4">NAME</th>
      </tr>
    </thead>
    <tbody>

    </tbody>
  </table>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
  <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

答案 1 :(得分:1)

var data = {};

$(document).ready(function () {
    $("#Search").click(function (any) {
		$("tbody").empty();
        var searchIds = new Set($('#searchBox').val().split(/[ ,\r\n]+/).map(s => s.trim()));
        searchIds.forEach(CODE =>
			
            $("tbody").append('<tr>' + `<td class="theader1" id="theader1">${CODE}</td>` + `<td class="theader2" id="theader2">${datab[CODE]}</td>` + `<td class="theader3" id="theader3">${datac[CODE]}</td>` + `<td class="theader4" id="theader4">${datad[CODE]}</td>` + '</tr>'));
    });
});

function getdata() {
    fetch("https://api.myjson.com/bins/f2nos").then(resp => resp.json()).then(resp => {
        datab = Object.assign({}, ...resp.features.map(
            ({ properties: { CODE, DIVISION}}) => ({ [CODE]: DIVISION}))
        );
        datac = Object.assign({}, ...resp.features.map(
            ({ properties: { CODE, PROVINCE}}) => ({ [CODE]: PROVINCE}))
        );
        datad = Object.assign({}, ...resp.features.map(
            ({ properties: { CODE, NAME}}) => ({ [CODE]: NAME}))
        );		
    });
}

getdata();						
	
/*Checkbox To Table Head*/
$(document).ready(function(e) {
    

$("input:checkbox:not(:checked)").each(function() {
	var apndcss='';
    var column = "table ." + $(this).attr("name");
	apndcss+=column+"{display:none;}";
	$('#appnedcss').html(apndcss)
    console.log(apndcss);
});

$("#chkbtn").on('change','input',function(){
var apndcss='';
$("#chkbtn input:checkbox").each(function() {
if($(this).is(":not(:checked)")){
var column = "table ." + $(this).attr("name");	
apndcss+=column+"{display:none;}";
}
})
$('#appnedcss').html(apndcss)
})
});
<!DOCTYPE html>
<html lang="en">
<head>
  <title>Bootstrap Example</title>
  <meta charset="utf-8">
  <meta name="viewport" content="width=device-width, initial-scale=1">
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
	<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
	<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
 <style id="appnedcss"></style> 
</head>
<body>

  <body>
	<span class="clearable">
		<input id="searchBox" type="text" rows="25" cols="15" WRAP="HARD" placeholder="Paste the list HERE" type="search">
	</span>
	<button class="button button1" id="Search">Search</button>	
	</br>
	<p id="chkbtn"><input type="checkbox" class="theader1" name="theader1" checked="checked"> CODE
  <input type="checkbox" class="theader2" name="theader2"  checked="checked"> DIVISION
  <input type="checkbox" class="theader3" name="theader3" checked="checked"> PROVINCE
  <input type="checkbox" class="theader4" name="theader4" checked="checked"> NAME</p>
	</br>
		<table border="1px" id="data">
			<thead>
			<tr>
			<th class="theader1" id="theader1">CODE</th>
			<th class="theader2" id="theader2">DIVISION</th>
			<th class="theader3" id="theader3">PROVINCE</th>	
			<th class="theader4" id="theader4">NAME</th>
			</tr>
			</thead>
			<tbody></tbody>
		</table>



</body>
</html>

相关问题