Read selected column in javascript from csv - javascript

I used a javascript to upload a csv file and did some cleaning,
I would like to only show 1 column out of everything in the csv file, any advice?
Here is my javascript
function Upload() {
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 cells = rows[i].split(",");
if (cells.length > 1) {
var row = table.insertRow(-1);
for (var j = 0; j < cells.length; j++) {
var cell = row.insertCell(-1);
cell.innerHTML = cells[j];
}
}
}
var dvCSV = document.getElementById("dvCSV");
dvCSV.innerHTML = "";
dvCSV.appendChild(table);
}
reader.readAsText(fileUpload.files[0]);
} else {
alert("This browser does not support HTML5.");
}
} else {
alert("Please upload a valid CSV file.");
}
}
HTML
<input type="file" id="fileUpload" />
<input type="button" id="upload" value="Upload" onclick="Upload()" />
<div id="dvCSV">
Any advice will be greatly appreciated.
Thanks in advance.

Instead of iterating over all the row cells, just output the one you want:
var targetIndex = rows[0].indexOf("Column name");
for (var i = 0; i < rows.length; i++) {
var cells = rows[i].split(",");
if (cells[targetIndex]) {
var row = table.insertRow(-1);
var cell = row.insertCell(-1);
cell.innerHTML = cells[targetIndex];
}
}

Related

Any way to automatically reload a file selected from "InputFile" through Filereader?

I am trying to display a CSV file into an HTML table.
I have it set up so that you can pick the CSV and it will successfully show in HTML format.
Is there anyway to refresh this so that if the selected file Changes, the HTML format will change with it (Without user input re-selected the file.
Code and Table are below. But basically I would like it so that if the population of New York changed in the table, that the HTML table is automatically updated as well.
<!DOCTYPE html>
<html lang="en">
<input type="file" id="fileUpload" onchange="Upload()"/>
<input type="button" id="upload" value="Upload" onclick="Upload()" />
<hr />
<div id="dvCSV">
</div>
<script type="text/javascript">
function Upload() {
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 cells = rows[i].split(",");
if (cells.length > 1) {
var row = table.insertRow(-1);
for (var j = 0; j < cells.length; j++) {
var cell = row.insertCell(-1);
cell.innerHTML = cells[j];
}
}
}
var dvCSV = document.getElementById("dvCSV");
dvCSV.innerHTML = "";
dvCSV.appendChild(table);
}
reader.readAsText(fileUpload.files[0]);
} else {
alert("This browser does not support HTML5.");
}
}
}
</script>
<script type="text/javascript">
Upload();
setInterval(function(){ Upload(); }, 10000);
</script>
</html>
rank
place
population
1
New York
8175133
2
Los Angeles
3792621
3
Chicago
2695598

display csv data in html page using java script

cvs data fileI am try to display the csv file data in a html table. I can display the data but in a incorrect formate.
I tried to split the column with ",". But the problem has a data in of the row some think like this "study period: Semester 1, 2019". The 2019 is showing in a different table.
<script type="text/javascript">
function Upload() {
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.on load = function (e) {
var table = document.createElement("table");
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++) {
var cell = row.insertCell(-1);
cell.innerHTML = cells[j];
}
}
}
var dvCSV = document.getElementById("dvCSV");
dvCSV.innerHTML = "";
dvCSV.appendChild(table);
}
reader.readAsText(fileUpload.files[0]);
} else {
alert("This browser does not support HTML5.");
}
} else {
alert("Please upload a valid CSV file.");
}
}
</script>
<input type="file" id="fileUpload" />
<input type="button" id="upload" value="Upload" on click="Upload()" />
<hr />
<div id="dvCSV">
</div>
i expected to get the result as entity in respective rows and column, but i am getting half of the data in one row and rest in another

select a specific text from a line of text

For example if this is a line of text which is placed inside a file : The sun rises in the East.
Also, in an HTML page it reads a text from a text box (say 'rises'). I need to check this text with the text inside the file to find a match. And I need to return the text value inside the file. How it can be performed? I am using JavaScript.
function Upload() {
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];
var radio = document.createElement('input');
radio.type = 'checkbox';
radio.name = 'check';
}
}
var button = document.createElement('button');
button.textContent = 'Send';
cell.appendChild(button);
var dvCSV = document.getElementById("dvCSV");
dvCSV.innerHTML = "";
dvCSV.appendChild(table);
}
reader.readAsText(fileUpload.files[0]);
} else {
alert("This browser does not support HTML5.");
}
} else {
alert("Please upload a valid CSV file.");
}
}
Read the text from the file i.e The sun rises in the East.
Now,compare this value to the value entered in the textbox by the user using string.search(textbox value), where string="text read from the file".

How to push values from a dropdown to an array and add the array to a table?

This is the JavaScript. The select has an id of 'counties'.
The table is to be inserted into a div called 'up_bottom'.
var leagueArray = [];
function addTeams() {
var county=document.getElementById("counties");
var val = county.options[county.selectedIndex].value;
leagueArray.push(val);
function display() {
var table = document.createElement("table");
for (var i=0; i<leagueArray.length; i++) {
var row = table.insertRow();
for (var j=0; j<leagueArray[i].length; j++) {
var cell = row.insertCell();
cell.appendChild(document.createTextNode(leagueArray[i]));
}
}
var tableDiv = document.getElementById("up_bottom");
tableDiv.appendChild(table);
}
display();
}
Please do the following Steps
Get Selected Value from Dropdown
Put the Selected Value into Array
Create A String of tr element and append it to Table before First tr element
Try this,
function addTeams(){
var leagueArray = [];
var county=document.getElementById("counties");
for (i = 0; i < county.options.length; i++) {
leagueArray[i] = county.options[i].value;
}
display(leagueArray);
}
function display(leagueArray) {
var table = document.createElement("table");
for (var i=0; i<leagueArray.length; i++) {
var row = table.insertRow();
for (var j=0; j<leagueArray[i].length; j++) {
var cell = row.insertCell();
cell.appendChild(document.createTextNode(leagueArray[i]));
}
}
var tableDiv = document.getElementById("up_bottom");
tableDiv.appendChild(table);
}
addTeams();

JavaScript reading data into an array from a dynamic table of textfields

I'm dynamically creating a table using an HTML table and JavaScript Functions attatched to button clicks. I now want to take the data and store it into multidimensional array (if possible) using another button named finished. I'm having trouble even getting started with the last method to save it into array. I can't figure out how to retrieve the text data.
Here is my current HTML code.
<head>
<title>TableTest</title>
<script src="/javascript/func.js"></script>
</head>
<body>
<form>
<div id="Input">
<INPUT class="form-button" id="AddRow" type="button" value="Add Row" onclick="addRow('dataTable')" />
<INPUT class="form-button" id="DeleteRow" type="button" value="Delete Row(s)" onclick="deleteRow('dataTable')" />
<INPUT class="form-button" id="Finished" type="button" value="Finished" onclick="gatherData('dataTable')" />
<table id="dataTable" border="1" style="width:200px" id="mytable" align="center" cellspacing="3" cellpadding="4">
<th>Select</th>
<th>Text1</th>
<th>Text2</th>
<th>Text3</th>
<tr>
<td><INPUT type="checkbox" name="chk"/></td>
<td><INPUT type="text" name="text1"/></td>
<td><INPUT type="text" name="txt2"/></td>
<td><INPUT type="text" name="txt3"/></td>
</tr>
</table>
</div>
</form>
</body>
Here is my JavaScript file:
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for(var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[1].cells[i].innerHTML;
//alert(newcell.childNodes);
switch(newcell.childNodes[0].type) {
case "text":
newcell.childNodes[0].value = "";
break;
case "checkbox":
newcell.childNodes[0].checked = false;
break;
}
}
}
function deleteRow(tableID) {
try {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for(var i=0; i<rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if(null != chkbox && true == chkbox.checked) {
if(rowCount <= 2) {
alert("Cannot delete all the rows.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}catch(e) {
alert(e);
}
}
function gatherData(){
//Tests
var table = document.getElementById('dataTable');
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
alert(rowCount);
alert(row);
alert(colCount);
}
I reworked TameBadger's answer to build the array by row instead of by column. I also added a check to see if the given cell has a value before referencing it. In my case, not all cells have values.
var table = document.getElementById('mainTable');
if (table === null)
return;
if (table.rows[0].cells.length <= 1)
return;
var tblData = [];
//Put a RowNumber name and values placeholder for the number of rows we have.
for (r = 0; r < table.rows.length; r++)
{
//Debug
//console.log(" row: ", r);
tblData.push({
name: "RowNumber" + r,
items: []
});
//Get the cells for this row.
var cells = table.rows[r].cells;
//Loop through each column for this row and push the value...
for (c = 0; c < cells.length; c++)
{
var inputElem = cells[c].children[0];
var tmpInputElem;
if (inputElem == null)
{
tmpInputElem = "";
}
else
{
tmpInputElem = inputElem.value
}
//Debug
//console.log(" row-cel: ", r, "-", c, " ", inputElem);
tblData[r].items.push(
{
//Comment out the type for now...
//inputType: inputElem.getAttribute('type'),
inputValue: tmpInputElem
});
}
}
//Debug
//printData(tblData);
I tried to keep it simple, and also jQuery clean, so to speak.
var data = [];
function gatherData() {
var table = document.getElementById('dataTable');
for (r = 1; r < table.rows.length; r++) {
var row = table.rows[r];
var cells = row.cells;
for (c = 0; c < cells.length; c++) {
var cell = cells[c];
var inputElem = cell.children[0];
var isInput = inputElem instanceof HTMLInputElement;
if (!isInput)
return;
var value = inputElem.value;
var isCheckbox = inputElem.getAttribute('type') == 'checkbox';
if (isCheckbox)
value = inputElem.checked;
var rowData = {};
rowData.inputType = inputElem.getAttribute('type');
rowData.inputValue = value;
data.push(rowData);
}
}
}
function startExec() {
gatherData();
for (i = 0; i < data.length; i++) {
console.log(data[i].inputType);
console.log(data[i].inputValue);
}
}
//just wait for the dom to load, and then execute the function for testing
document.addEventListener("DOMContentLoaded", startExec, false);
2nd Revision
function getData() {
var table = document.getElementById('dataTable');
if (table === null)
return;
if (table.rows[0].cells.length <= 1)
return;
var data = [];
for (l = 0; l < table.rows[0].cells.length; l++) {
data.push({
items: [],
name: "ColumnNumber" + l
});
}
for (i = 1; i < table.rows.length; i++) {
var cells = table.rows[i].cells;
for (c = 0; c < cells.length; c++) {
var inputElem = cells[c].children[0];
data[c].items.push({
inputType: inputElem.getAttribute('type'),
inputValue: inputElem.value
});
}
}
printData(data);
}
function printData(data) {
for (i = 0; i < data.length; i++) {
for (k = 0; k < data[i].items.length; k++) {
console.log(data[i].items[k].inputValue);
}
}
}
document.addEventListener("DOMContentLoaded", getData(), false);
It's great that you're starting off and doing the table manipulation yourself, and I would recommend continuing that, if you want to peak into a bigger codebase I would recommend checking out jTable's. Even though it's a jQuery plugin, you'll still be able to learn something from looking at the code structure for handling all the logic surrounding building a table according to a dataset and adding records etc.
Is this what you are looking for?
JSFIDDLE
$(document).ready(function(){
$('#Finished').click(function(){
var my_arr=[];
$('td').each(function(){
if ($(this).children().is(':checkbox') )
{
if($(this).children().prop('checked'))
{
my_arr.push($(this).children().val());
}
}else{
my_arr.push($(this).children().val());
}
})
console.log(my_arr);
})
})

Categories

Resources