I am running into a problem here. I parse a .CSV file and I need to show them into a DataTables format.
The problem is The markups are all inside javascript as shown below
$("#upload").bind("click", function () {
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.csv|.xlsx|.xls)$/;
if (regex.test($("#fileUpload").val().toLowerCase())) {
if (typeof (FileReader) != "undefined") {
var reader = new FileReader();
reader.onload = function (e) {
var table = $("<table id='comp-monitor' class='table table-condensed table-striped'> \n\
<tr><th>No.</th><th>DESKRIPSI ASSEMBLY</th><th>Drawing No.</th><th>QTY3</th><th>WEIGHT</th><th>-</th></tr>");
var rows = e.target.result.split("\n");
var no = 0;
for (var i = 0; i < rows.length; i++) {
no++;
// console.log(i);
var row = $("<tr />");
var cells = rows[i].split(",");
// Column No
var cell_no = $("<td />");
cell_no.html(no);
row.append(cell_no);
for (var j = 0; j < cells.length; j++) {
var cell = $("<td />");
cell.html(cells[j]);
row.append(cell);
}
table.append(row);
}
$("#dvCSV").html('');
$("#dvCSV").append(table);
}
reader.readAsText($("#fileUpload")[0].files[0]);
} else {
alert("This browser does not support HTML5.");
}
} else {
alert("Please upload a valid CSV file.");
}
});
and the jquery initialization is just outside that function
$('#comp-monitor').DataTable();
Somehow the datatables doesn't run and I need some help with this where to put the initialization.
Thanks a bunch,
You can Initialize the datatable inside javascript itself
$("#upload").bind("click", function () {
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.csv|.xlsx|.xls)$/;
if (regex.test($("#fileUpload").val().toLowerCase())) {
if (typeof (FileReader) != "undefined") {
var reader = new FileReader();
reader.onload = function (e) {
var table = $("<table id='comp-monitor' class='table table-condensed table-striped'> \n\
<tr><th>No.</th><th>DESKRIPSI ASSEMBLY</th><th>Drawing No.</th> <th>QTY3</th><th>WEIGHT</th><th>-</th></tr>");
var rows = e.target.result.split("\n");
var no = 0;
for (var i = 0; i < rows.length; i++) {
no++;
// console.log(i);
var row = $("<tr />");
var cells = rows[i].split(",");
// Column No
var cell_no = $("<td />");
cell_no.html(no);
row.append(cell_no);
for (var j = 0; j < cells.length; j++) {
var cell = $("<td />");
cell.html(cells[j]);
row.append(cell);
}
table.append(row);
}
$("#dvCSV").html('');
$("#dvCSV").append(table);
//HERE
$('#comp-monitor').DataTable();
}
reader.readAsText($("#fileUpload")[0].files[0]);
} else {
alert("This browser does not support HTML5.");
}
} else {
alert("Please upload a valid CSV file.");
}
});
let me know if this work.
I found an answer by using addrow
var t = $('#comp-monitor').DataTable({
});
$("#upload").bind("click", function () {
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.csv|.xlsx|.xls)$/;
if (regex.test($("#fileUpload").val().toLowerCase())) {
if (typeof (FileReader) != "undefined") {
var reader = new FileReader();
reader.onload = function (e) {
var table = $("#comp-monitor tbody");
var rows = e.target.result.split("\n");
var no = 0;
table.empty();
for (var i = 0; i < rows.length; i++) {
no++;
var row = $("<tr class='odd' role='row' />");
var cells = rows[i].split(",");
t.row.add([
no,
cells[0],
cells[1],
cells[2],
cells[3],
cells[4]
]).draw(false);
table.append(row);
}
}
reader.readAsText($("#fileUpload")[0].files[0]);
} else {
alert("This browser does not support HTML5.");
}
} else {
alert("Please upload a valid CSV file.");
}
});
Related
In below code I am trying to create two HTML dynamic tables, but it doesn't work.
One table with ID "Table" and another one with ID "Tabled".
<script type="text/javascript">
function Upload() {
const columns = [0, 3] // represents allowed column 1 and 3 in index form
const dccolumns = [0, 3] // represents allowed column 1 and 3 in index form
var fileUpload = document.getElementById("fileUpload");
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.csv|.txt)$/;
if (regex.test(fileUpload.value.toLowerCase())) {
if (typeof (FileReader) != "undefined") {
var reader = new FileReader();
reader.onload = function (e) {
var table = document.createElement("table");
table.id = 'table'
var tabledc = document.createElement("tabled");
tabled.id = 'tabled'
var rows = e.target.result.split("\n");
for (var i = 0; i < rows.length; i++) { var cells = rows[i].split(","); if (cells.length > 1) {
var row = table.insertRow(-1);
for (var j = 0; j < cells.length; j++) {
// ignore columns that are not allowed
if (!columns.includes(j)) {
continue
}
var rc = cells[j];
if (rc == "SUMMARY") {
var cell = row.insertCell(-1);
cell.innerHTML = cells[j];
alert(rc);
}
}
}
}
var dvCSV = document.getElementById("dvCSV");
dvCSV.innerHTML = "";
dvCSV.appendChild(table);
var alld = document.getElementById("alld");
alld.innerHTML = "";
alld.appendChild(tabled);
}
reader.readAsText(fileUpload.files[0]);
} else {
alert("This browser does not support HTML5.");
}
} else {
alert("Please upload a valid CSV file.");
}
}
When I run above code it just updates table in "Table", but not in "Tabled". I am not sure what wrong I am doing here.
Thanks
I am able to display the content from a csv file on a web page ( based on what I have found on this site), but how do I read the csv values into an array in JavaScript?
Let's say if I have a file in this CSV format:
Red, Green, Blue,,
Orange, Yellow, Black,,
Indigo, purple, navy,, ...
I appreciate any help.
function UploadCSV() {
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) {
try{
var table = $("<table />");
var rows = e.target.result.split("\n");
for (var i = 0; i < rows.length; i++) {
var row = $("<tr />");
var cells = rows[i].split("|");
if (cells.length > 1) {
for (var j = 0; j < cells.length; j++) {
var cell = $("<td />");
var td = cells[j].replace(/[^\x00-\x7F]/g, "");
cell.text(td);
row.append(cell);
}
table.append(row);
}
}
$("#dvCSV").html('');
$("#dvCSV").append(table);
}
catch(e)
{
$('#meessageBar1').text(e.message);
$('#meessageBar1').fadeIn("slow", function () {
setTimeout(messageBar1Remove, 2000);
});
}
}
reader.readAsText($("#fileUpload")[0].files[0]);
} else {
$('#meessageBar1').text('This browser does not support HTML5.');
$('#meessageBar1').fadeIn("slow", function () {
setTimeout(messageBar1Remove, 2000);
});
}
}
}
This is a snippet I used to read data from a PIPE ('|') seperated csv file data into HTML table, you can var cells = rows[i].split("|"); change this line whatever your csv file use as seperator. Here I attach each cell data of each row into of a table row, you can omit this and simply insert whole data into an array. If this helps you, please mark it as accepted answer. Thank you.
I'm a beginner in JS and I'm unfortunately stuck on how to display the information that will be filtered by what a user puts in the input. Right now I have a table that will display the JSON info but I would like to filter like a letter or full name like "Trump", which will then will display a table of results. How would I combine the results that are filtered to make it into a table with the code I have?
The HTML
<form>
<label for="name">Name:</label>
<input id='input' placeholder="President Name" type="text">
<button onclick="loadPresidents()" type="button">Search for Presidents</button> <button type="button">Clear</button>
<div id="presidentialTable"></div>
</form>
The JS
function loadPresidents() {
"use strict";
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function () {
if (this.readyState === 4 && this.status === 200) {
var data = this.responseText,
jsonResponse = JSON.parse(data),
table = document.createElement('table');
table.setAttribute('class', 'history');
var properties = ['number', 'name', 'date', 'took_office', 'left_office'];
var capitalize = function (s) {
return s.charAt(0).toUpperCase() + s.slice(1);
};
function filterResults() {
var input = document.getElementById('input').value;
var resultsFiltered = jsonResponse.filter(function(historicalData) {
return historicalData.indexOf(input) != -1;
});
var result = '';
resultsFiltered.map(function(a) {
result += a + '<br/>';
});
}
var tr = document.createElement('tr');
for (var i = 0; i < properties.length; i++) {
var th = document.createElement('th');
th.appendChild(document.createTextNode(capitalize(properties[i])));
tr.appendChild(th);
}
table.appendChild(tr);
var tr, row;
for (var r = 0; r < jsonResponse["presidents"].president.length; r++) {
tr = document.createElement('tr');
row = jsonResponse["presidents"].president[r];
for (var i = 0; i < properties.length; i++) {
var td = document.createElement('td');
td.appendChild(document.createTextNode(row[properties[i]]));
tr.appendChild(td);
}
table.appendChild(tr);
}
document.getElementById('presidentialTable').appendChild(table);
}
};
xhttp.open("GET", "//Resources/USPresidents.json", true);
xhttp.send();
}
Rewrite the code as follows - https://jsfiddle.net/7gt2be1x/2/
function loadPresidents() {
"use strict";
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState === 4 && this.status === 200) {
var data = this.responseText,
jsonResponse = JSON.parse(data),
table = document.createElement('table');
table.setAttribute('class', 'history');
var properties = ['number', 'name', 'date', 'took_office', 'left_office'];
var capitalize = function(s) {
return s.charAt(0).toUpperCase() + s.slice(1);
};
function filterResults(data) {
var input = document.getElementById('input').value;
return data.filter(function(historicalData) {
return historicalData.name.toLowerCase().indexOf(input.toLowerCase()) != -1;
});
}
var tr = document.createElement('tr');
for (var i = 0; i < properties.length; i++) {
var th = document.createElement('th');
th.appendChild(document.createTextNode(capitalize(properties[i])));
tr.appendChild(th);
}
table.appendChild(tr);
var tr, row;
var filtered = filterResults(jsonResponse["presidents"].president);
for (var r = 0; r < filtered.length; r++) {
tr = document.createElement('tr');
row = filtered[r];
for (var i = 0; i < properties.length; i++) {
var td = document.createElement('td');
td.appendChild(document.createTextNode(row[properties[i]]));
tr.appendChild(td);
}
table.appendChild(tr);
}
document.getElementById('presidentialTable').appendChild(table);
}
};
xhttp.open("GET", "//schwartzcomputer.com/ICT4570/Resources/USPresidents.json", true);
xhttp.send();
}
I created an input field which basically works as a Multiselect comboBox (I want to do it in pure Javascript). So on click of input field, I am opening one table, (Option tag will work better but here I am using table.)
Something I am missing and because of that I am not able to open my table. Can you please help me what is missing here.
My not working code.
JS
MyCombo = function(args) {
debugger;
var dataUrl = args.url;
var divID = args.divID;
var div = document.getElementById(divID);
var input = document.createElement("input");
input.type = "text";
input.id = "textfield";
var divTrigger = document.createElement("div");
divTrigger.id = "triggers";
var crossImage = document.createElement("img");
var dropImg = document.createElement("img");
crossImage.className = "trigger";
dropImg.className = "trigger";
crossImage.src = "css/delete.png";
dropImg.src = "css/combo_arrow.png";
crossImage.id = "arrow";
dropImg.id = "cross";
crossImage.onclick = deleteValue;
dropImg.onclick = DropDownExpand;
divTrigger.appendChild(crossImage);
divTrigger.appendChild(dropImg);
div.appendChild(input);
div.appendChild(divTrigger);
var dropDownTable = document.createElement('table');
dropDownTable.id = "myTable";
var headerTr = document.createElement('tr');
headerTr.className = 'header';
var innerTr = document.createElement('tr');
var innerTd = document.createElement('td');
innerTr.appendChild(innerTd);
dropDownTable.appendChild(headerTr);
dropDownTable.appendChild(innerTr);
div.appendChild(dropDownTable);
function foo(callback) {
var httpRequest = new XMLHttpRequest();
httpRequest.open('GET', "data.json", true);
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState === XMLHttpRequest.DONE && httpRequest.status === 200) {
callback(httpRequest.responseText);
}
};
httpRequest.send();
}
foo(function(data) {
var jsonc = JSON.parse(data);
var new_opt = "";
for (i = 0; i < jsonc.length; i++) {
new_opt += '<tr><td>' + jsonc[i]['VALUE'] + '</td></tr>';
}
document.getElementById('myTable').innerHTML = new_opt;
document.querySelectorAll('#myTable tr:not(.header)').forEach(function(_tr) {
_tr.addEventListener('click', function() {
document.getElementById('textfield').value += " ; " + this.getElementsByTagName('td')[0].textContent;
});
});
});
}
function DropDownExpand(){
var input, filter, table, tr, td, i;
table = document.getElementById("myTable");
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[0];
if (td) {
if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}
function deleteValue(){
debugger;
}
By another idea things are working file. Here is my code.
My Working code
JS
MyCombo = function(args) {
var dataUrl = args.url;
var divID = args.divID;
var div = document.getElementById(divID);
var myTable = '<input type="text" class="Autocombo-combobox"; style="width:30%;" id="myInput" onkeyup="myFunction()" title="Type in a name">' +
'<table id="myTable">' + '<tr class="header"></tr>' + '<tr><td></td></tr>' + '</table>';
div.innerHTML = myTable;
function foo(callback) {
var httpRequest = new XMLHttpRequest();
httpRequest.open('GET', "data.json", true);
httpRequest.onreadystatechange = function() {
if (httpRequest.readyState === XMLHttpRequest.DONE && httpRequest.status === 200) {
callback(httpRequest.responseText);
}
};
httpRequest.send();
}
foo(function(data) {
var jsonc = JSON.parse(data);
var new_opt = "";
for (i = 0; i < jsonc.length; i++) {
new_opt += '<tr><td>' + jsonc[i]['VALUE'] + '</td></tr>';
}
document.getElementById('myTable').innerHTML = new_opt;
document.querySelectorAll('#myTable tr:not(.header)').forEach(function(_tr) {
_tr.addEventListener('click', function() {
document.getElementById('myInput').value += " ; " + this.getElementsByTagName('td')[0].textContent;
});
});
});
myFunction = function() {
debugger;
var input, filter, table, tr, td, i;
table = document.getElementById("myTable");
tr = table.getElementsByTagName("tr");
for (i = 0; i < tr.length; i++) {
td = tr[i].getElementsByTagName("td")[0];
if (td) {
if (td.innerHTML.toUpperCase().indexOf(filter) > -1) {
tr[i].style.display = "";
} else {
tr[i].style.display = "none";
}
}
}
}
}
I can not find many difference between these two. But Still having some issue in the first one. Can you please help me to understand.
I've uploaded a CSV-file to an HTML page via javascript. The CSV rows are: name and email-address, e.g. rambo,rambo#rambo.com.
How to SEARCH the 'name' from these loaded CSV-file?
Also, one of the data is an email-address and I want to send a mail to that email-address. Is that value retrieved to a variable?
My code to search each elements:
function Search() {
var fileUpload = document.getElementById("fileUpload");
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.csv|.txt)$/;
if (regex.test(fileUpload.value.toLowerCase())) {
if (typeof (FileReader) != "undefined") {
var reader = new FileReader();
reader.onload = function (e) {
var table = document.createElement("table");
var rows = e.target.result.split("\n");
for(var i = 0; i < rows.length; i++)
{
var row = table.insertRow(-1);
var cells = rows[i].split(",");
for(var j = 0; j < cells.length; j++)
{
var cell = row.insertCell(-1);
// cell.innerHTML = cells[j];
// Here repeated checkboxes:
var radio = document.createElement('input');
radio.type = 'checkbox';
radio.name = 'check';
}
var ser=document.getElementById("texts");
if(cells[i].indexOf(ser))
{
alert("matches");
cell.innerHTML = cells[i];
}
else
{
alert("unmatches");
}
var cell = row.insertCell(-1);
cell.appendChild(radio);
//cell.appendChild(button);
}
var button = document.createElement('button');
button.textContent = 'Send';
cell.appendChild(button);
button.onclick = function(){ alert();};
var dvCSV = document.getElementById("dvCSV");
dvCSV.innerHTML = "";
dvCSV.appendChild(table);
}
reader.readAsText(fileUpload.files[0]);
}
}
}
Ad search: indexOf() is your friend here. This should give you a figure:
var table = $('#your-table'),
searchstring = 'your-searchstring';
searchstring.toLowerCase();
for (var i = 0, cell; cell = table.cells[i]; i++) {
if (cell.indexOf(searchstring)) {
// I don't know what you want to do with the search-results...
// ..but you can do it here.
}
}
Ad email-address: you can add the address to a variable in your CSV-import:
var cells = rows[i].split(","),
address = cells[1];
I'd suggest making an array addresses and fill it each row.