I want to create a script in JS that produces color boxes according to the numerical value of the CSV data provided. So far, I have only managed to pass the data into an HTML table and I'm looking for two things;
- Change the rgb background-color of
<td>s according to the number inserted (eg. a value of 128 gives rgb(128,0,0)) - Leave the cell content blank but still create a new
<td>element.
Here's my script;
<html>
<head>
<meta http-equiv="content-type" content="text/html; charset=utf-8" />
</head>
<body >
<div>
<form class="form-horizontal well">
<fieldset>
<label for="csvFileInput"> <strong>CSV File:</strong>
</label>
<input type="file" id="csvFileInput" onchange="handleFiles(this.files)"
accept=".csv">
</div>
</fieldset>
</form>
<div id="output">
</div>
</div>
<footer>
</footer>
<script type="text/javascript" >
function handleFiles(files) {
if (window.FileReader) {
getAsText(files[0]);
} else {
alert('FileReader are not supported in this browser.');
}
}
function getAsText(fileToRead) {
var reader = new FileReader();
reader.onload = loadHandler;
reader.onerror = errorHandler;
reader.readAsText(fileToRead);
}
function loadHandler(event) {
var csv = event.target.result;
processData(csv);
}
function processData(csv) {
var allTextLines = csv.split(/\r\n|\n/);
var lines = [];
while (allTextLines.length) {
lines.push(allTextLines.shift().split(','));
}
document.getElementById("output").innerHTML = (lines);
drawOutput(lines);
}
function errorHandler(evt) {
if(evt.target.error.name == "NotReadableError") {
alert("Canno't read file !");
}
}
function drawOutput(lines){
document.getElementById("output").innerHTML = "";
var table = document.createElement("table");
for (var i = 0; i < lines.length; i++) {
var row = table.insertRow(-1);
for (var j = 0; j < lines[i].length; j++) {
var firstNameCell = row.insertCell(-1);
firstNameCell.appendChild(document.createTextNode(lines[i][j]));
}
}
document.getElementById("output").appendChild(table);
}
</script>
</body>
</html>