过滤行并在屏幕

时间:2016-10-01 05:22:31

标签: javascript jquery html css csv

我使用csv文件在屏幕上填充了表格。我需要使用逗号分隔的ID值(例如1,2,8,34)过滤此表,并仅在点击按钮'过滤器'中显示这些值中使用的行。

HTML文件 -

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html>
<html>
<head>
    <title>Hello there</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <script src="http://code.jquery.com/jquery-1.11.1.min.js" type="text/javascript"> </script>
    <!--<script type="text/javascript" src="JavaScript.js"></script>-->
    <script type="text/javascript" src="JavaScript2.js"></script>


    <style>
        table, th, td {
            border: 1px solid black;
            border-collapse: collapse;
        }

        th, td {
            padding: 15px;
        }

        th {
            text-align: left;
        }

        table {
            border-spacing: 5px;
        }

        .guide {
            text-decoration: underline;
            text-align: center;
        }

        .odd {
            color: #fff;
            background: #666;
        }

        .even {
            color: #666;
        }

        .hot {
            border: 1px solid #f00;
        }
    </style>

</head>
<body>

    <div class="container">
        <div class="row">
            <h2>aaaaaaaaaaaaaaaaa</h2>            
        </div>
        <div class="panel panel-primary">
            <div class="panel-heading">pppppp</div>
            <div class="panel-body">
                <div class="row">
                    <div class="col-sm-12 col-sm-offset-1">

                        <form id="form1" runat="server" class="form-horizontal">
                            <div class="form-group">
                                <div class="col-sm-5">
                                    <div class="col-sm-6">
                                        <input type="file" accept=".csv" id="fileUpload" /></div>
                                    <div class="col-sm-6">
                                        <input type="button" id="upload" class="btn btn-primary" value="Upload" /></div>

                                </div>
                                <div class="col-sm-7">
                                    <div class="col-sm-2">
                                        <input type="button" id="cancel" class="btn btn-primary btn pull-right" value="Cancel/Save" style="visibility: hidden" /></div>
                                    <div class="col-sm-2">
                                        <input type="button" id="process" class="btn btn-primary btn pull-right" value="Process" style="visibility: hidden" /></div>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>

                <div class="row">
                    <div class="col-sm-12">
                        <div class="panel panel-default" style="align-self: center">
                            <div class="panel-body" style="max-height: 400px; min-height: 400px; overflow-y: scroll;">
                                <div class="row">
                                    <div class="col-sm-12">
                                        <center>
                                                        <div class="input-append" id="filterDev" style="visibility:hidden">
                                                          <input name="search" id="inputFilter" placeholder="Enter ID to filter" />
                                                             <input type="button" value="Filter" id="filter" class="btn btn-primary" />
                                                                </div></center>
                                    </div>
                                    <br />
                                    <br />

                                </div>
                                <div class="row">
                                    <div class="col-sm-12" id="dvCSV"></div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="row">
                  <div class="col-sm-12"><p id="download" style="color:cornflowerblue; visibility:hidden"><strong>Please click the below links to download the processed file..</strong></p></div>
                </div>
                <div class="row">
                     <div class="col-sm-12">
                         <div class="col-sm-3"><p id="File1" style="color:cornflowerblue;text-decoration:underline;visibility:hidden">File1 Download</p></div>
                         <div class="col-sm-3"><p id="File2" style="color:cornflowerblue;text-decoration:underline;visibility:hidden">File2 Download</p></div>
                     </div>
                </div>
            </div>
        </div>
    </div>


</body>
</html>
<script type="text/javascript">

$("#cancel").on("click", function() {
    $('input:checked').each( function() {
        $( this ).closest("tr").remove();
    });
});

$('#inputFilter').keyup(function () {
    var that = this;
    $.each($('tr'),
    function (i, val) {
        if ($(val).text().indexOf($(that).val()) == -1) {
            $('#name').animate({
                marginTop: 0
            },
            50,
            function () {
                $('tr').eq(i).hide();
            });
        } else {
            $('#name').animate({
                marginTop: 0
            },
            50,
            function () {
                $('tr').eq(i).show();
            });
        }
    });
});

$(function () {
    $("#process").bind("click", function () {

        document.getElementById("File1").style.visibility = "visible";
        document.getElementById("File2").style.visibility = "visible";
        document.getElementById("download").style.visibility = "visible";

    });

});

</script>

JavaScript2.js

$(function () {
    $("#upload").bind("click", function () {

        var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.csv|.txt)$/;
        if (regex.test($("#fileUpload").val().toLowerCase())) {
            if (typeof (FileReader) != "undefined") {
                var reader = new FileReader();
                reader.onload = function (e) {
                    var table = $("<table id='name'/>");
                    var rows = e.target.result.split("\n");
                    for (var i = 0; i < rows.length; i++) {
                        var row = $("<tr />");
                        var cells = rows[i].split(",");

                        $("<td/>").html('<input type="checkbox" id='+cells[0]+'>').appendTo(row);
                        //alert(cells[0]);
                        for (var j = 0; j < cells.length; j++) {

                            $("<td/>").html('<input type="text" disabled value=' +cells[j]+ '>').appendTo(row);
                        }
                        table.append(row);
                    }
                    $("#dvCSV").html('');
                    $("#dvCSV").append(table);
                    document.getElementById("cancel").style.visibility = "visible";
                    document.getElementById("process").style.visibility = "visible";
                    document.getElementById("filterDev").style.visibility = "visible";
                    //document.getElementById("filter").style.visibility = "visible";

                }
                reader.readAsText($("#fileUpload")[0].files[0]);
            } else {
                alert("This browser does not support HTML5.");
            }
        } else {
            alert("Please upload a valid CSV file.");
        }

    });
});

这样的事情 -

ExamplePicture

修改#1

使用@ user3273700的脚本后,尽管过滤器功能有效,但每次我的表的最后一列显示“未定义”时。 csv文件看起来像这样 -

CSV file uploaded

表格看起来像这样 -

Table

修改后的HTML -

<%@ Page Language="C#" AutoEventWireup="true" CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html>
<html>
<head>
    <title>J---</title>
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1">
    <link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css">
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>
    <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>
    <script src="http://code.jquery.com/jquery-1.11.1.min.js" type="text/javascript"> </script>
    <!--<script type="text/javascript" src="JavaScript.js"></script>-->
    <script type="text/javascript" src="JavaScript4.js"></script>


    <style>
        table, th, td {
            border: 1px solid black;
            border-collapse: collapse;
        }

        th, td {
            padding: 15px;
        }

        th {
            text-align: left;
        }

        table {
            border-spacing: 5px;
        }

        .guide {
            text-decoration: underline;
            text-align: center;
        }

        .odd {
            color: #fff;
            background: #666;
        }

        .even {
            color: #666;
        }

        .hot {
            border: 1px solid #f00;
        }
    </style>

</head>
<body>

    <div class="container">
        <div class="row">
            <h2>SAS</h2>
        </div>
        <div class="panel panel-primary">
            <div class="panel-heading">Aa</div>
            <div class="panel-body">
                <div class="row">
                    <div class="col-sm-12 col-sm-offset-1">

                        <form id="form1" runat="server" class="form-horizontal">
                            <div class="form-group">
                                <div class="col-sm-5">
                                    <div class="col-sm-6">
                                        <input type="file" accept=".csv" id="fileUpload" />
                                    </div>
                                    <div class="col-sm-6">
                                        <input type="button" id="upload" class="btn btn-primary" value="Upload" />
                                    </div>

                                </div>
                                <div class="col-sm-7">
                                    <div class="col-sm-2">
                                        <input type="button" id="cancel" class="btn btn-primary btn pull-right" value="Cancel/Save" style="visibility: hidden" />
                                    </div>
                                    <div class="col-sm-2">
                                        <input type="button" id="process" class="btn btn-primary btn pull-right" value="Process" style="visibility: hidden" />
                                    </div>
                                </div>
                            </div>
                        </form>
                    </div>
                </div>

                <div class="row">
                    <div class="col-sm-12">
                        <div class="panel panel-default" style="align-self: center">
                            <div class="panel-body" style="max-height: 400px; min-height: 400px; overflow-y: scroll;">
                                <div class="row">
                                    <div class="col-sm-12">
                                        <center>
                                                        <div class="input-append" id="filterDev" style="visibility:hidden">
                                                          <input name="search" id="inputFilter" placeholder="Enter ID to filter" />
                                                             <input type="button" value="Filter" id="filter" class="btn btn-primary" />
                                                                </div></center>
                                    </div>
                                    <br />
                                    <br />

                                </div>
                                <div class="row">
                                    <div class="col-sm-12" id="dvCSV">
                                        <table id="my-table">

                                        </table>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>

                <div class="row">
                    <div class="col-sm-12">
                        <p id="download" style="color: cornflowerblue; visibility: hidden"><strong>Please click the below links to download the processed file..</strong></p>
                    </div>
                </div>
                <div class="row">
                    <div class="col-sm-12">
                        <div class="col-sm-3">
                            <p id="File1" style="color: cornflowerblue; text-decoration: underline; visibility: hidden">File1 Download</p>
                        </div>
                        <div class="col-sm-3">
                            <p id="File2" style="color: cornflowerblue; text-decoration: underline; visibility: hidden">File2 Download</p>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>


</body>
</html>
<script type="text/javascript">

    $("#cancel").on("click", function () {
        $('input:checked').each(function () {
            $(this).closest("tr").remove();
        });
    });


    $(function () {
        $("#process").bind("click", function () {

            document.getElementById("File1").style.visibility = "visible";
            document.getElementById("File2").style.visibility = "visible";
            document.getElementById("download").style.visibility = "visible";

        });

    });

    $("#filter").click(function () {
        ids = $("#inputFilter").val();
        if (ids != "") {
            idsArray = ids.split(",");
            $("#my-table tr:gt(0)").hide();
            $.each(idsArray, function (i, v) {
                $("#my-table tr[data-id=" + v + "]").show();
            })
        } else {
            $("#my-table tr").show();
        }
    });

</script>

修改后的JavaScript4.js -

$(function () {
    $("#upload").bind("click", function () {

        var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.csv|.txt)$/;
        if (regex.test($("#fileUpload").val().toLowerCase())) {
            if (typeof (FileReader) != "undefined") {
                var reader = new FileReader();
                reader.onload = function (e) {
                    //var table = $("<table id='name'/>");
                    var lines = e.target.result.split("\n");
                    var result = [];
                    var headers = lines[0].split(",");
                    //alert(headers);

                    for (var i = 1; i < lines.length; i++) {
                        var obj = {};
                        var currentline = lines[i].split(",");

                        for (var j = 0; j < headers.length; j++) {
                            obj[headers[j]] = currentline[j];
                        }
                        result.push(obj);
                    }


                    populateTable(result);
                    document.getElementById("cancel").style.visibility = "visible";
                    document.getElementById("process").style.visibility = "visible";
                    document.getElementById("filterDev").style.visibility = "visible";
                }
                reader.readAsText($("#fileUpload")[0].files[0]);
            }
        }

    });
});

$(function () {
    $("#process").bind("click", function () {

        document.getElementById("File1").style.visibility = "visible";
        document.getElementById("File2").style.visibility = "visible";

    });

});

function populateTable(finalObject) {

    var obj = finalObject;
    var table = $("<table id='my-table' />");
    table[0].border = "1";
    var columns = Object.keys(obj[0]);

    var columnCount = columns.length;
    var row = $(table[0].insertRow(-1));

    for (var i = 0; i < columnCount; i++) {
        var headerCell = $("<th />");
        headerCell.html([columns[i]]);
        row.append(headerCell);
    }

    $.each(obj, function (i, obj) {
        row = '<tr data-id="' + obj.ID + '"><td>' + obj.ID + '</td><td>' + obj.NAME + '</td><td>' + obj.CITY + '</td><td>' + obj.ADDRESS + '</td></tr>';
        table.append(row);
    });


    var dvTable = $("#dvCSV");
    dvTable.html("");
    dvTable.append(table);

}

2 个答案:

答案 0 :(得分:0)

您可以在向表中附加行时向每行添加自定义属性(data-id),然后使用此引用过滤表格。

试试这个工作样本

&#13;
&#13;
$(function() {
  var data = [{
    id: "1",
    name: "Ravi",
    city: "Mumbai",
    address: "Address1",
    designation: "programer"
  }, {
    id: "2",
    name: "Mohit",
    city: "Delhi",
    address: "Address1",
    designation: "Project Manager"
  }, {
    id: "3",
    name: "Mohan",
    city: "Mumbai",
    address: "Address1",
    designation: "CEO"
  }, {
    id: "4",
    name: "John",
    city: "Landon",
    address: "Address1",
    designation: "programer"
  }, {
    id: "5",
    name: "Jane",
    city: "Landon",
    address: "Address1",
    designation: "programer"
  }];


  //set table header
  var headRow = '<tr>';
  $.each(data[0], function(attr, val) {
    headRow += '<th>' + attr + '</th>'
  });
  headRow += '</tr>';
  $("#my-table").append(headRow);

  //add data rows to table

  $.each(data, function(i, obj) {
    row = '<tr data-id="' + obj.id + '"><td>' + obj.id + '</td><td>' + obj.name + '</td><td>' + obj.city + '</td><td>' + obj.address + '</td><td>' + obj.designation + '</td></tr>';
    $("#my-table").append(row);
  });

  $("#filter-btn").click(function() {
    ids = $("#filter-box").val();
    if (ids != "") {
      idsArray = ids.split(",");
      $("#my-table tr:gt(0)").hide();
      $.each(idsArray, function(i, v) {
        $("#my-table tr[data-id=" + v + "]").show();
      })
    } else {
      $("#my-table tr").show();
    }
  });
});
&#13;
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="filter-box">
<button id="filter-btn">filter</button>
<table id="my-table">

</table>
&#13;
&#13;
&#13;

我希望它会有所帮助

答案 1 :(得分:0)

你得到的是未定义的,因为它读取标题行的最后一列为“ADDRESS \ r \ n”(带回车符)而不是“ADDRESS”。当你用它来制作你的对象数组时,它会设置一个属性“ADDRESS \ r”而不是“ADDRESS”。

所以你需要将它从头文件数组中删除。

var headers = lines[0].split(",").map(function(obj){
    return obj.replace(/(?:\\[rn]|[\r\n]+)+/g,''); 
});

这是一个工作小提琴https://jsfiddle.net/1av8gzo5/