Getting ID of checked rows on a grid in javascript - javascript

I am displaying a grid with some data fetched from a csv file along with a checkbox before each row. I am also saving unique ID in the value property of checkbox. Now I want to get the value of ID`s of all checked check boxes in alert() when 'Cancel' button is clicked.
html-
<div class="panel panel-primary">
<div class="panel-heading">DIS Automation</div>
<div class="panel-body">
<div class="field_row">
<input type="file" accept=".csv" id="fileUpload" name="fileUpload1" />
</div>
<br />
<div class="field_row">
<div class="col-lg-12">
<div class="form-group">
<center><div class="col-lg-3"><div class="input-append" id="filterDev" style="visibility: hidden">
<input name="search" id="inputFilter" placeholder="Enter comma separated ID" />
<input type="button" value="Filter" id="filter" class="btn btn-primary" />
</div></div></center>
<div class="col-lg-6"></div>
<input type="button" id="upload" value="Upload" class="btn btn-primary" />
<input type="button" id="cancel" value="Cancel/Save" style="visibility: hidden" class="btn btn-primary" />
<input type="button" id="process" value="Process" style="visibility: hidden" class="btn btn-primary" />
</div>
</div>
<div class="row">
<div class="col-lg-12">
<div class="panel panel-default" style="align-self: center">
<div class="panel-body" style=" max-height:600px; min-height: 400px; overflow-y: scroll;">
<div class="row">
<div class="col-sm-12" id="dvCSV">
<table id="my-table">
</table>
</div>
</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>
<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();
}
});
/* $("#File1").click(function () {
window.location = "Files/CommitteeMembers.xlsx";
});
$("#File1").click(function () {
window.location = "Files/GSD_Offering_Completion.xlsx";
});*/
</script>
Javascript-
$(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");
//alert(lines);
var result = [];
var headers = lines[0].split(",");
for (var i = 1; i < headers.length; i++) {
var header = headers[i];
header = header.replace(/(\r\n|\n|\r)/gm, "");
headers[i] = header;
}
for (var i = 1; i < lines.length; i++) {
var obj = {};
var currentline = lines[i].split(",");
//alert(currentline);
for (var j = 0; j < headers.length; j++) {
obj[headers[j]] = currentline[j];
//alert(obj[headers[j]]);
}
result.push(obj);
//alert(JSON.stringify(result));
}
//alert(result[0].NAME + ' '+ result[0].ADDRESS+" "+result[0].CITY);
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]);
columns.unshift('');
//alert(columns);
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><input type="checkbox" value='+obj.ID+'/></td>
table.append(row);
});
var dvTable = $("#dvCSV");
dvTable.html("");
dvTable.append(table);
}
How can this be implemented??

This is a sample code of how you can do it:
$(".btnCancel").click(function(){
var alertText="";
$("[type='checkbox']:checked").each(function(){
alertText+= $(this).attr("value") + " ";
});
alert(alertText);
});
Here is the JSFiddle demo

Related

new input replace Instead of append

Here is the html that I wrote for program
It's working but append is not working.
<script src="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/js/bootstrap.bundle.min.js"></script>
<link href="https://cdn.jsdelivr.net/npm/bootstrap#5.1.3/dist/css/bootstrap.min.css" rel="stylesheet"/>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="container m-5">
<div class="row">
<div class="col-md-6 justify-content-center">
<span>Full Name :</span>
<input id="name" type="name" class="d-flex mb-3">
<span>Email :</span>
<input id="email" type="email" name="email" class="d-flex mb-3">
<span>Comment :</span>
<input id="comment" type="text" class="d-flex mb-3">
<button id="btn" class="mt-3">Submit</button>
</div>
<div class="col-md-6">
<p id="demo"></p>
</div>
</div>
</div>
name and comment are inputs.
I type some text but append doesn't working and the new text that entered replace the first one.
function SubmitComment(name, comment) {
let newComment = censor(comment)
for (let i = 0; i < name.length; i++) {
let demo = $("#demo");
demo.html("")
demo.append(`
<h4>${name.val()} :</h4>
<br>
<p>${newComment}</p>
`)
}
}
function censor(comment) {
var splitString = comment.val().split(" ")
for (let b = 0; b < splitString.length; b++) {
if (splitString[b] == "duck") {
splitString[b] = '****';
}
if (splitString[b] == "swan") {
splitString[b] = '****';
}
}
var joinArray = splitString.join(" ");
return joinArray;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
Am not sure why your looping the name property, but here is a working example!
function Submit() {
SubmitComment($('.name'), $('.comment'));
}
function SubmitComment(name, comment) {
let newComment = censor(comment)
let demo = $("#demo");
demo.html("")
for (let i = 0; i < name.length; i++) {
demo.append(`
<h4>${name.val()} :</h4>
<br>
<p>${newComment}</p>
`)
}
}
function censor(comment) {
var splitString = comment.val().split(" ")
for (let b = 0; b < splitString.length; b++) {
if (splitString[b] == "duck") {
splitString[b] = '****';
}
if (splitString[b] == "kilt") {
splitString[b] = '****';
}
}
var joinArray = splitString.join(" ");
return joinArray;
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<input class="name" />
<input class="comment" />
<button onClick="Submit()">Submit</button>
<div id="demo"></div>

Search <div> for text using, javasccript

I don't know javascript but I want to use, search on my site. I found a good example on stackoverflow link
I joined all the parts and received the following code:
function SearchName() {
var input = document.getElementById("Search");
var filter = input.value.toLowerCase();
var nodes = document.getElementsByClassName('target');
var card = document.getElementsByClassName('card');
for (i = 0; i < nodes.length; i++) {
if (nodes[i].innerText.toLowerCase().includes(filter)) {
card[i].style.display = "block";
} else {
card[i].style.display = "none";
}
}
}
<input id="Search" onkeyup="SearchName();" class="form-control dsh191" type="text" placeholder="search" name="" />
<div class="d-flex m-0 p-0">
<div class="card">
Abc Def
<p class="dsh185">Code: <span class="code">1234</span></p>
</div>
<div class="card">
Qwr Tyu
<p class="dsh185">Code: <span class="code">5678</span></p>
</div>
<div class="card">
Iop Klj
<p class="dsh185">Code: <span class="code">9000</span></p>
</div>
</div>
Everything works fine, but I need to search by class = 'code'. My question is:
How do I search for Qwr Tyu and <p class="dsh185">Code: <span class="code">5678</span></p> ? What did I try?
I duplicated javascript function code and changed the class from target to code, but nothing was received, now the search goes after the first function in the input.
I added a new function to the input SearchCode();;
In <span>5678</span> I added class="code"
And as I said above I dubbed javascript code and I changed 2 variables: from nodes to code new class name and from card to profilecard, only the new variable but the html tag remains the same.
function SearchName() {
var input = document.getElementById("Search");
var filter = input.value.toLowerCase();
var nodes = document.getElementsByClassName('target');
var card = document.getElementsByClassName('card');
for (i = 0; i < nodes.length; i++) {
if (nodes[i].innerText.toLowerCase().includes(filter)) {
card[i].style.display = "block";
} else {
card[i].style.display = "none";
}
}
}
function SearchCode() {
var input = document.getElementById("Search");
var filter = input.value.toLowerCase();
var code = document.getElementsByClassName('code');
var profilecard = document.getElementsByClassName('card');
for (i = 0; i < code.length; i++) {
if (code[i].innerText.toLowerCase().includes(filter)) {
profilecard[i].style.display = "block";
} else {
profilecard[i].style.display = "none";
}
}
}
<input id="Search" onkeyup="SearchName(); SearchCode();" class="form-control dsh191" type="text" placeholder="search" name="" />
<div class="d-flex m-0 p-0">
<div class="card">
Abc Def
<p class="dsh185">Code: <span class="code">1234</span></p>
</div>
<div class="card">
Qwr Tyu
<p class="dsh185">Code: <span class="code">5678</span></p>
</div>
<div class="card">
Iop Klj
<p class="dsh185">Code: <span class="code">9000</span></p>
</div>
</div>
My question: How can I search the site after 2 html tags (Search by text in tags)?
Any idea how I can change the code, or where I went wrong etc ... Thanks
one idea can be to use innerText on parent tag profileCard
function SearchName() {
var input = document.getElementById("Search");
var filter = input.value.toLowerCase();
var nodes = document.getElementsByClassName('target');
var card = document.getElementsByClassName('card');
for (i = 0; i < nodes.length; i++) {
if (nodes[i].innerText.toLowerCase().includes(filter)) {
card[i].style.display = "block";
} else {
card[i].style.display = "none";
}
}
}
function SearchCode() {
var input = document.getElementById("Search");
var filter = input.value.toLowerCase();
var code = document.getElementsByClassName('code');
var profilecard = document.getElementsByClassName('card');
for (i = 0; i < code.length; i++) {
if (profilecard[i].innerText.toLowerCase().includes(filter)) {
profilecard[i].style.display = 'block';
} else {
profilecard[i].style.display = 'none';
}
}
}
<input id="Search" onkeyup="SearchName(); SearchCode();" class="form-control dsh191" type="text" placeholder="search" name="" />
<div class="d-flex m-0 p-0">
<div class="card">
Abc Def
<p class="dsh185">Code: <span class="code">1234</span></p>
</div>
<div class="card">
Qwr Tyu
<p class="dsh185">Code: <span class="code">5678</span></p>
</div>
<div class="card">
Iop Klj
<p class="dsh185">Code: <span class="code">9000</span></p>
</div>
</div>

WebChat how to set css color for sender/receiver

I am working on implementing a web chat and have come up with an issue that I hope is easily solvable.
How do I change the color for the sender/receiver to differenciate them?
I have tried to saving the colors into my db but the issue is how I can identify that I am the sender and the receivers color needs to be different.
This is how I have implemented my chat:
Chat.js
connection.on("SessionNotification", function (user, message) {
var msg = message.replace(/&/g, "&").replace(/</g, "<").replace(/>/g, ">");
var p = document.createElement("span");
var q = document.createElement("li");
p.setAttribute("class", "Sender");
q.setAttribute("class", "Message");
p.textContent = user + " - " + moment(datetime).format("DD-MM-YYYY HH:mm:ss");
q.textContent = msg;
document.getElementById("MessageList").appendChild(p);
document.getElementById("MessageList").appendChild(q);
});
Html
<script>
$(document).ready(function () {
$('#MessageList').stop().animate({
scrollTop: $('#MessageList')[0].scrollHeight
}, 2000);
var SessionId = document.getElementById("Id").value;
console.log(SessionId);
var form_data = {
"SessionId": SessionId
};
$.ajax({
url: "#Url.Action("GetHistory", #ViewContext.RouteData.Values["controller"].ToString())",
method: "POST",
data: JSON.stringify(form_data),
contentType: "application/json",
success: function (result) {
console.log(result);
var output = JSON.parse(result);
for (var i = 0; i < output.length; i++) {
var p = document.createElement("span");
var q = document.createElement("li");
p.setAttribute("class", "Sender");
q.setAttribute("class", "Message");
p.textContent = output[i].Name + " - " + moment(output[i].CreatedOn).format("DD-MM-YYYY HH:mm:ss");
q.textContent = output[i].Message;
document.getElementById("MessageList").appendChild(p);
document.getElementById("MessageList").appendChild(q);
}
},
error: function (error) {
console.log(error);
}
});
return false;
});
</script>
<div class="col-sm-12">
<h2>Session</h2>
<hr />
</div>
<div class="col-sm-12">
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<div id="MessageListContainer">
<ul id="MessageList">
</ul>
</div>
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="form-group">
#Html.HiddenFor(m => m.Id)
#Html.HiddenFor(m => m.CurrentUser)
<input class="form-control col-sm-12" id="Message" type="text" />
</div>
</div>
</div>
<div class="row">
<div class="col-sm-12">
<div class="form-group">
<div class="clearfix">
<div class="pull-right">
<input id="Send" type="button" value="Send" class="btn btn-primary" />
</div>
</div>
</div>
</div>
</div>
<div class="col-sm-12">
<hr />
</div>
</div>
<script src="~/aspnet/signalr/dist/browser/signalr.js"></script>
<script src="~/js/chat.js"></script>
Your AJAX call that comes back as JSON appears to have a few fields like Name and CreatedOn. You can add an additional field server side for the SessionId, which you are injecting server-side anyway into your HTML. Then you can compare to see if the message's session matches yours. If so, then it is you and not the receiver. So you might have something like:
JS
// You set this earlier on
var SessionId = document.getElementById("Id").value;
// ........ OTHER CODE IN BETWEEN
for (var i = 0; i < output.length; i++) {
var p = document.createElement("span");
var q = document.createElement("li");
// If session ID matches current session (i.e. you) then add different class
if (output[i].SessionId === SessionId) {
// It is you
p.setAttribute("class", "Sender");
} else {
// It is other person
p.setAttribute("class", "Receiver");
}
q.setAttribute("class", "Message");
p.textContent = output[i].Name + " - " + moment(output[i].CreatedOn).format("DD-MM-YYYY HH:mm:ss");
q.textContent = output[i].Message;
document.getElementById("MessageList").appendChild(p);
document.getElementById("MessageList").appendChild(q);
}
CSS
.Sender {
color: blue;
}
.Receiver {
color: green;
}

Linking two pages

I am working on trying to link pages together so if a person were to login using the login page, they would be redirected to a specific created page, and if a user clicked the register button, they would be redirected to the register page and from there, after inputting in information, they would be directed to another page. The button for login or register does not work. Is there a way to fix this?
So far I have this for my login page.
function login() {
var users = ["admin1", "admin2", "admin3", "admin4"];
var pass = ["pass1", "pass2", "pass3", "pass4"];
ivar aUser = document.getElementById("user_name").value;
var aPass = document.getElementById("password").value;
for (i = 0; i < users.length; i++) {
if (users[i] == aUser && pass[i] == aPass) {
window.location = "dashboard.php";
break;
}
}
var myOut = document.getElementById("output");
myOut.innerHTML = "Who Are You? / Incorrect Password";
myOut.className = "error";
function init() {
var login_button = document.getElementById("login_button");
if (login_button !== null) {
login_button.onclick = login;
}
var register_button = document.getElementById("register_button");
if (register_button !== null) {
register_button.onclick = validation;
}
for (i = 1; i <= 10; i++) {
var myErr = document.getElementById("err" + i);
if (myErr !== null) {
myErr.className = "error";
}
}
}
<h1>
Please Login
</h1>
<form id="order_form">
<fieldset>
<legend>Login</legend>
<div class="tab">
<div class="tRow">
<div class="tRow">
<div class="tCell">
<label for="user_name">User Name:</label>
</div>
<div class="tCell">
<input type="text" id="user_name" maxlength="50" />
</div>
</div>
<!-- END OF THIS SELECTION -->
<div class="tRow> <div class=">
<label for="password">Password:</label>
</div>
<div class="tCell">
<input type="text" id="password" required="" maxlength="50" />
</div>
</div>
<!-- END OF THIS SELECTION -->
<div class="tRow">
<div class="tCell">
</div>
<div class="tCell">
<input type="button" id="login_button" value="Login" />
</div>
</div>
<!--END OF THIS SELECTION-->
<div class="tRow">
<div class="tCell">
</div>
<div class="tCell">
<input type="button" id="register_button" value="Register Now!" />
</div>
</div>
<!--END OF THIS SELECTION-->
</div>
<!-- END OF THE TABLE -->
<br />
<div id="output" class="error"></div>
</fieldset>
</form>
Validation function:
function validation() {
for (i=1; i<=10; i++) {
var myErr = document.getElementById("err" + i);
myErr.innerHTML = "";
}
document.getElementById("output").innerHTML = "";
var dept_name = document.getElementById("dept_name").value;
var user_email = document.getElementById("user_email").value;
var user_password = document.getElementById("user_password").value;
var phone_number = document.getElementById("phone_number").value;
var first_name = document.getElementById("first_name").value;
var last_name = document.getElementById("last_name").value;
var office_location = document.getElementById("office_location").value;
var valid = true;
if (dept_name == "") {
document.getElementById("err1").innerHTML = "Invalid!";
valid = false;
}
if ((user_email) =="") {
valid = false;
document.getElementById("err2").innerHTML = "Invalid!";
}
if ((user_password) =="") {
valid = false;
document.getElementById("err3").innerHTML = "Invalid!";
}
if ((first_name) =="") {
valid = false;
document.getElementById("err4").innerHTML = "Invalid!";
}
if ((last_name) =="") {
valid = false;
document.getElementById("err5").innerHTML = "Invalid!";
}
if (isNaN(phone_number) || card_number.length !==11) {
valid = false;
document.getElementById("err6").innerHTML = "Invalid!";
}
if ((office_location) =="") {
valid = false;
document.getElementById("err7").innerHTML = "Invalid!";
}
}
window.onload=init;
Several errors
missing brackets
no execution of init
missing validation function
This works:
function login() {
var myOut = document.getElementById("output");
var users = ["admin1", "admin2", "admin3", "admin4"];
var pass = ["pass1", "pass2", "pass3", "pass4"];
var aUser = document.getElementById("user_name").value;
var aPass = document.getElementById("password").value;
for (i = 0; i < users.length; i++) {
if (users[i] == aUser && pass[i] == aPass) {
myOut.innerHTML = "Correct - you will be redirected";
setTimeout(function() {
window.location = "dashboard.php";
},1000);
return;
}
}
myOut.innerHTML = "Who Are You? / Incorrect Password";
myOut.className = "error";
}
function init() {
var login_button = document.getElementById("login_button");
if (login_button !== null) {
login_button.onclick = login;
}
var register_button = document.getElementById("register_button");
if (register_button !== null) {
register_button.onclick = validation;
}
for (i = 1; i <= 10; i++) {
var myErr = document.getElementById("err" + i);
if (myErr !== null) {
myErr.className = "error";
}
}
}
function validation() { /* you need some code here */ }
window.onload=init;
<h1>
Please Login
</h1>
<form id="order_form">
<fieldset>
<legend>Login</legend>
<div class="tab">
<div class="tRow">
<div class="tRow">
<div class="tCell">
<label for="user_name">User Name:</label>
</div>
<div class="tCell">
<input type="text" id="user_name" maxlength="50" />
</div>
</div>
<!-- END OF THIS SELECTION -->
<div class="tRow> <div class=">
<label for="password">Password:</label>
</div>
<div class="tCell">
<input type="text" id="password" required="" maxlength="50" />
</div>
</div>
<!-- END OF THIS SELECTION -->
<div class="tRow">
<div class="tCell">
</div>
<div class="tCell">
<input type="button" id="login_button" value="Login" />
</div>
</div>
<!--END OF THIS SELECTION-->
<div class="tRow">
<div class="tCell">
</div>
<div class="tCell">
<input type="button" id="register_button" value="Register Now!" />
</div>
</div>
<!--END OF THIS SELECTION-->
</div>
<!-- END OF THE TABLE -->
<br />
<div id="output" class="error"></div>
</fieldset>
</form>
You can make the test simpler:
var userPos = users.indexOf(aUser);
if (userPos !=-1 && userPos === pass.indexOf(aPass)) {
...
}

Filter rows and show only selected ones on screen

I have populated the table on screen using a csv file. I need to filter this table using comma separated ID values(e.g 1,2,8,34) and show only those rows used in these values on the click of button 'Filter'.
HTML file -
<%# 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.");
}
});
});
Something like this -
EDIT#1
After using the script by #user3273700 , though the filter functionality works but every time the last column of my table shows 'Undefined'. The csv file looks like this -
And the table looks like this -
Modified 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>
Modified 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);
}
You can add a custom attribute (data-id) to each row while you append rows to your table and then use this reference to filter your table.
Try this working sample
$(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();
}
});
});
<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>
I hope it will help
You are getting as undefined because it read last column of header row as "ADDRESS\r" (with a carriage return) instead of "ADDRESS". And when you use it to make your array of objects it set a property "ADDRESS\r" instead "ADDRESS".
So you need to remove it from your headers array like this.
var headers = lines[0].split(",").map(function(obj){
return obj.replace(/(?:\\[rn]|[\r\n]+)+/g,'');
});
Here is a working fiddle https://jsfiddle.net/1av8gzo5/

Categories