How to display contents of multi upload files? - javascript

Here, there is an example to show contents of one upload file.
.js
$scope.uploadFilename = function (files) {
if (!files[0]) {
return;
}
var reader = new FileReader();
reader.onload = function (e) {
var str = reader.result;
var csv = str.split(/\n/);
var headers = csv[0].split(',');
var str_result = '';
for (var i = 1; i < csv.length - 1; i++) {
var curline = csv[i].split(',');
var tmp = '' + curline[1];
if (i == csv.length - 2) {
str_result += tmp.split('"').join('');
} else {
str_result += tmp.split('"').join('') + '\n';
}
}
angular.element('#upload_keywords_list').val(str_result);
$scope.uploadedKeywordsCount = csv.length - 2;
};
reader.readAsText(files[0]);
};
.html
<div class="chosefile">
<div class="clearfix">
<input type="file" name="file" class="pull-left" onchange="angular.element(this).scope().uploadFilename(this.files)">
<textarea id="upload_keywords_list" class="form-control" rows="10"></textarea>
<div class="uploaded-keywords-count" ng-if="uploadedKeywordsCount > 0">
<strong>Total number: </strong>{{ uploadedKeywordsCount }}
</div>
</div>
</div>
I want to show contents of multi upload files.
Can you tell me the method how to do it?
And then, how to change the value of total number, when i edit the contents of textarea that I've already opened?
Thanks.

Hope this works.
I removed uploaded-keywords-count and textarea from your html. And added a new div
<div id="textAreaContainer"></div>
Also i made changes to your script. I wrapped your code inside for loop
Now, you can select multiple files, at once or one by one it doesn't matter.
And if you try to select the same file again, it warns you. and rejects the file again.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>
<div ng-app="fileApp" ng-controller="myCtrl">
<script>
var app = angular.module('fileApp', []);
app.controller('myCtrl', function($scope) {
var allFiles = [];
$scope.uploadFilename = function (files) {
if (!files[0]) {
return;
}
cnt = files.length;
for (var k = 0; k < cnt; k++) {
if(!allFiles.includes(files[k].name)) {
var reader = new FileReader();
reader.fileName = files[k].name;
allFiles.push(reader.fileName);
reader.onload = function (e) {
var str = e.target.result;
var csv = str.split(/\n/);
var headers = csv[0].split(',');
var str_result = '';
for (var i = 1; i < csv.length - 1; i++) {
var curline = csv[i].split(',');
var tmp = '' + curline[1];
if (i == csv.length - 2) {
str_result += tmp.split('"').join('');
} else {
str_result += tmp.split('"').join('') + '\n';
}
}
$scope.uploadedKeywordsCount = csv.length - 2;
var containerData = "";
containerData += '<div id="fileContent' + k + '"><textarea>' + str_result + '</textarea>';
containerData += '<span>' + $scope.uploadedKeywordsCount + '</span></div>'
var containerHtml = $(containerData);
angular.element('#textAreaContainer').append(containerHtml);
};
reader.readAsText(files[k]);
//console.log(files[k]);
} else {
alert('File already exists');
}
}
}
});
$(document).on('keyup', 'textarea', function(){
$(this).closest("div").find('span').html($(this).val().split(/\n/).length);
})
</script>
<div class="chosefile">
<div class="clearfix">
<input type="file" name="file" class="pull-left" onchange="angular.element(this).scope().uploadFilename(this.files)" multiple>
<div id="textAreaContainer"></div>
</div>
</div>
</div>
I forgot to tell you that i added a new script for your second question. Now you can edit the textarea, and the lines count changes.

Related

Reorder CSV rows

I have this code which basically reads a CSV and should output a table where the CSV row content should be reordered!
Example :
fish;4;1;33
fish should be at 1 row column 4.
dog;5;2;66
dog should be at 2nd row column 5
The problem is that it doesn't print anything, neither at the console! Can you please show me where I am wrong? What modifications should I do?
My code:
function processFile() {
var fileSize = 0;
var theFile = document.getElementById("myFile").files[0];
if (theFile) {
var table = document.getElementById("myTable");
var headerLine = "";
var myReader = new FileReader();
myReader.onload = function(e) {
var content = myReader.result;
var lines = content.split("\r");
for (var i = 0; i <lines.length; i++)
{
document.write("<th>");
document.write(" ");
document.write("</th>");
}
for (var i = 0; i <lines.length; i++)
{
document.write("<tr>");
for (var j = 0; j <lines.length; j++)
{
document.write("<td>");
document.write(" ");
document.write("</td>");
}
document.write("</tr>");
}
function insertData(id, content) {
var dataRows = content.split("\r");
if (table) {
dataRows.forEach(function(s) {
var x = s.split(';');
table.rows[x[2]].cells[x[1]].textContent = x[0];
});
}
}
}
myReader.readAsText(theFile);
}
return false;
} //end
So, i did everything again for you with a big example.
I think you can handle it in your code, or take mine in the example.
Here are the main functions you can safely use in your case :
//for swapping values
function swap(arr, a, b){
var tmp = arr[a];
arr[a] = arr[b];
arr[b] = tmp;
return arr;
}
//for reorder lines a<=>b
function reorderLine(csvArray,a,b){
return swap(csvArray,a,b);
}
//for reorder one col values a<=>b
function reorderColumn(csvLine,a,b){
return swap(csvLine.split(";"),a,b).join(';');
}
// create a table with csv data
function csvArrayToTable(csvArray,selectorId){
var html = ["<table cellpadding='10' border='1'>"];
csvArray.map(function(lines){
html.push("<tr>");
var cols = lines.split(";");
html.push("<th>"+cols[0]+"</th>");
cols.shift();
cols.map(function(val){
html.push("<td>"+val+"</td>");
});
html.push("</tr>");
});
html.push("</table>");
document.getElementById(selectorId).innerHTML = html.join('');
}
And a working example you can use too, upload file is included (click on Run code snippet at the bottom of the post, and full page to test) :
//for swapping values
function swap(arr, a, b){
var tmp = arr[a];
arr[a] = arr[b];
arr[b] = tmp;
return arr;
}
//for reorder lines a<=>b
function reorderLine(csvArray,a,b){
console.log('reorderLine',csvArray,a,b);
return swap(csvArray,a,b);
}
//for reorder one col values a<=>b
function reorderColumn(csvLine,a,b){
console.log('reorderColumn',csvLine,a,b);
return swap(csvLine.split(";"),a,b).join(';');
}
// create a table with csv data
function csvArrayToTable(csvArray,selectorId){
var html = ["<table cellpadding='10' border='1'>"];
csvArray.map(function(lines){
html.push("<tr>");
var cols = lines.split(";");
html.push("<th>"+cols[0]+"</th>");
cols.shift();
cols.map(function(val){
html.push("<td>"+val+"</td>");
});
html.push("</tr>");
});
html.push("</table>");
document.getElementById(selectorId).innerHTML = html.join('');
}
// init element
var rawCsvFile = document.getElementById("csvInput");
var rawCsv = document.getElementById("rawCsv");
var reorderedRawCsv = document.getElementById("reorderedRawCsv");
var lines = document.getElementById("lines");
var lineA = document.getElementById("lineA");
var lineB = document.getElementById("lineB");
var colA = document.getElementById("colA");
var colB = document.getElementById("colB");
var apply = document.getElementById("apply");
var reset = document.getElementById("reset");
var rawCsvData, reorderCsvData;
// file uploaded
rawCsvFile.addEventListener("change", function() {
// reader
var reader = new FileReader();
// the file is loaded
reader.onload = function(e) {
// cancel if undefined
if(!reader.result || typeof reader.result != "string") return;
// Get result from new FileReader()
rawCsvData = reader.result.split(/[\r\n]+/g); // split lines
rawCsv.innerHTML = reader.result; // show in textarea
reorderedRawCsvData = rawCsvData; // clone data at start
function showCsvValueInForm(){
// empty fields
lines.innerHTML = "";
lineA.innerHTML = "";
lineB.innerHTML = "";
colA.innerHTML = "";
colB.innerHTML = "";
// Show in Raw CSV textarea
reorderedRawCsv.innerHTML = reorderedRawCsvData.join("\r\n");
// Add All option in On
var toAll = document.createElement('option');
toAll.value = "all";
toAll.innerHTML = "All";
lines.appendChild(toAll);
// handle line change
reorderedRawCsvData.map(function(val,i){
var lineOpt = document.createElement('option');
lineOpt.value = i;
lineOpt.innerHTML = i + " - " +(val.split(';'))[0];
// add options in line selects
lines.appendChild(lineOpt.cloneNode(!!1));
lineA.appendChild(lineOpt.cloneNode(!!1));
lineB.appendChild(lineOpt);
});
// handle col change
var nCol = rawCsvData[0].split(';');
nCol.map(function(val,i){
var colOpt = document.createElement('option');
colOpt.value = i;
colOpt.innerHTML = i;
// add options in col selects
colA.appendChild(colOpt.cloneNode(!!1));
colB.appendChild(colOpt);
});
// create table
csvArrayToTable(reorderedRawCsvData,"reorderedCsvTable");
}
// fill select, option and table with the reordered csv data
showCsvValueInForm();
// apply event, change the order
apply.addEventListener("click", function() {
// reordering line
var lineAOpt = lineA.options[lineA.selectedIndex].value;
var lineBOpt = lineB.options[lineB.selectedIndex].value;
if(lineAOpt !== lineBOpt) reorderedRawCsvData = reorderLine(reorderedRawCsvData,lineAOpt,lineBOpt);
// reordering col (all or only one)
var colAOpt = colA.options[colA.selectedIndex].value;
var colBOpt = colB.options[colB.selectedIndex].value;
if(colAOpt !== colBOpt)
if(lines.value == "all"){
reorderedRawCsvData = reorderedRawCsvData.map(function(val,i){
return reorderColumn(val,colAOpt,colBOpt);
});
}else{
reorderedRawCsvData[lines.value] = reorderColumn(reorderedRawCsvData[lines.value],colAOpt,colBOpt);
}
// fill again
showCsvValueInForm();
});
// reset the form with raw values
reset.addEventListener("click", function() {
if (confirm("Are you sure ?")) {
// reset
reorderedRawCsvData = rawCsvData;
// fill again
showCsvValueInForm();
}
});
}
// read the uploaded csv file as text
reader.readAsText(event.target.files[0], 'utf-8');
});
body { padding:10px; background:#eee; text-align: left; font-family: sans-serif; }
fieldset { width:80%; background:#fff; }
<html>
<head>
<title>CSV Reorder</title>
</head>
<body>
<h1>Reorder CSV</h1>
<fieldset>
<h3>Step 1 - Raw CSV</h3>
<small>Load a CSV file (not nested)</small>
<br />
<input type="file" id="csvInput">
<br />
<br />
<div>
<textarea id="rawCsv" placeholder="Waiting for a file..."></textarea>
</div>
</fieldset>
<br />
<fieldset>
<h3>Step 2 - Reordering Option</h3>
<small>Choose how to order the CSV data</small>
<br />
<table>
<tr>
<td>Line</td>
<td><select id="lineA"></select></td>
<td><=></td>
<td><select id="lineB"></select></td>
</tr>
<tr>
<td>Column</td>
<td><select id="colA"></select></td>
<td><=></td>
<td><select id="colB"></select></td>
<td>on</td>
<td><select id="lines"></select></td>
</tr>
<tr>
<td colspan="4"><button id="apply">Apply</button> <button id="reset">Reset</button></td>
</tr>
</table>
</fieldset>
<br />
<fieldset>
<h3>Step 3 - Reordered CSV</h3>
<small>Get the reordered values</small>
<br />
<div>
<textarea id="reorderedRawCsv" placeholder="Waiting for options..."></textarea>
</div>
<div>
<h3>Reordered CSV in a table</h3>
<div id="reorderedCsvTable">
<small>Waiting for a file..</small>
<br />
</div>
</div>
</fieldset>
</body>
</html>
Enjoy !

how to display the previous user input along with the new input

I am new to Html and I am trying to create a script to display user input back to the user.whenever i am entering a new input,the new user input over rides the previous input. but i need to display all the user inputs? how to do it using Javascript.
my code
<html><head></head><body>
<input id="title" type="text" >
<input type="submit" value="Save/Show" onclick="clearAndShow()" />
<div id="display2letter"></div>
<div id="display3letter"></div>
<div id="display4letter"></div>
<script type="text/javascript">
var titleInput = document.getElementById("title");
var display2letter = document.getElementById("display2letter");
var display3letter = document.getElementById("display3letter");
var display4letter = document.getElementById("display4letter");
function clearAndShow () {
// Split input box value by comma
titles = titleInput.value.split(",");
// Reset display divs
display2letter.innerHTML = "";
display3letter.innerHTML = "";
display4letter.innerHTML = "";
// Cache length so it's not recalculated on each iteration.
var len = titles.length;
var twoletter = [];
var threeletter = [];
var fourletter =[];
for (i = 0; i < len; i++) {
// Check for a-z, A-Z,
if (!titles[i].match(/^[a-zA-Z]/)) {
throw error("Please use only alphabet letters");
}
// Dump into storage arrays.
if(titles[i].length == 2) {
twoletter.push(titles[i]);
}
else if(titles[i].length == 3){
threeletter.push(titles[i]);
}
else if(titles[i].length == 4){
fourletter.push(titles[i]);
}
}
display2letter.innerHTML += " 2 letters: " + twoletter.join(", ") + "<br/>";
display3letter.innerHTML += " 3 letters: " + threeletter.join(", ") + "<br/>";
display4letter.innerHTML += " 4 letters: " + fourletter.join(", ") + "<br/>";
}
</script>
</body>
</html>
Try declaring these variables -
var twoletter = [];
var threeletter = [];
var fourletter =[];
before the clearAndShow () function, ie,
<script type="text/javascript">
var titleInput = document.getElementById("title");
var display2letter = document.getElementById("display2letter");
var display3letter = document.getElementById("display3letter");
var display4letter = document.getElementById("display4letter");
var twoletter = [];
var threeletter = [];
var fourletter =[];
function clearAndShow () {

How To Change Image in Array Based on Textbox input in JavaScript?

I'm trying to make my page so a user can type a number value between 1 and 200 to get to whichever image they want to view. I've played around with the code, but I can't seem to get anything to work. Below is my code that I've tried to do this with. What am I doing wrong?
Edit: New Code:
`
<html>
<head>
<title></title>
</head>
<body style="background-color: teal;">
<form>
<center>
<div width="50%" style="width: 50%;">
<div id="main" align="middle">
<img src="page1.jpg" alt="" id="mainImg" height="90%">
</div>
<div id="imglist">
<a href="javascript:previousImage('mainImg')"><img src="previous.png" alt=""
align="left"></a>
<input id="myid" name="myid" size="3" type="text"></input>
<img src="next.png" alt="" align="right">
<script>
var imgArray = new Array();
var imgs = [];
for (var i = 0; i < 200; i++) {
imgs[i] = new Image();
imgs[i].src = "page" + (i + 1) + ".jpg";
}
function nextImage(element)
{
var img = document.getElementById(element);
for(var i = 0; i < imgArray.length;i++)
{
if(imgArray[i].src == img.src) // << check this
{
if(i === imgArray.length){
document.getElementById(element).src = imgArray[0].src;
break;
}
document.getElementById(element).src = imgArray[i+1].src;
break;
}
}
}
function previousImage(element)
{
var img = document.getElementById(element);
for(var i = 0; i < imgArray.length;i++)
{
if(imgArray[i].src == img.src)
{
if(i === 0){
document.getElementById(element).src = imgArray[imgArray.length-1].src;
break;
}
else{
document.getElementById(element).src = imgArray[i-1].src;
break;
}
}
}
}
window.onload = function() {
var elm = document.getElementById("myid"),
var img = document.getElementById("mainImg");
elm.onkeyup = function(event) {
if (this.value) {
var num = parseInt(this.value, 10);
if (num >= 1 && num <= 200 {
img.src = "page" + num + ".jpg";
}
}
}
}
</script>
</div>
</div>
</center>
</form>
</body>
</html>
Perhaps you mean for this:
if (this.value.length === 1,2,3) {
to be this:
if (this.value.length <= 3) {
In addition, I think you want to be converting the whole input value to a number, not using the individual keycodes.
I might suggest this different/simpler way of doing this that is much more DRY (don't repeat yourself):
// preload images
var imgs = [];
for (var i = 0; i < 200; i++) {
imgs[i] = new Image();
imgs[i].src = "page" + (i + 1) + ".jpg";
}
window.onload = function() {
var elm = document.getElementById("myid");
var img = document.getElementById("mainImg");
elm.onkeyup = function(event) {
if (this.value) {
var num = parseInt(this.value, 10);
if (num >= 1 && num <= 200) {
img.src = "page" + num + ".jpg";
}
}
}
}
Working Demo: http://jsfiddle.net/jfriend00/4dqbP/
Summary of changes:
Preload images in a loop rather than copied code
Construct image names dynamically
Make img variable to a local variable rather than an implicit global with var in front of it
Check to see if the input field is empty
Use parseInt() to parse the value of the input field into a number
Range check the parsed number
If in valid range, then construct the image name using that number

submitting csv form data with jquery then showing as json

I am a beginner in jquery so this may be stupid.
I want to take csv data from the user and transform it into json. Found a nice library but don't quite understand how the submitting is done in jquery.
For instance if I have a view
<script type="text/javascript" src="<?php echo site_url('public/js/jquery.js') ?>" ></script>
<script type="text/javascript" src="<?php echo site_url('javascript/main.js') ?>" ></script>
<div id="message"><p></p></div>
<form id="convertForm" name="convertForm" onsubmit="return false; ">
CSV<br /><textarea id="csv" name="csv" rows="10" cols="60"></textarea><br /><br />
JSON<br /><textarea id="json" name="json" rows="10" cols="60" readonly="readonly"></textarea><br /><br />
<input type="button" value="Convert" id="submitButton"/> <input type="reset" />
</form>
And the main.js file
function parseCSVLine (line)
{
line = line.split(',');
for (var i = 0; i < line.length; i++)
{
var chunk = line[i].replace(/^[\s]*|[\s]*$/g, "");
var quote = "";
if (chunk.charAt(0) == '"' || chunk.charAt(0) == "'") quote = chunk.charAt(0);
if (quote != "" && chunk.charAt(chunk.length - 1) == quote) quote = "";
if (quote != "")
{
var j = i + 1;
if (j < line.length) chunk = line[j].replace(/^[\s]*|[\s]*$/g, "");
while (j < line.length && chunk.charAt(chunk.length - 1) != quote)
{
line[i] += ',' + line[j];
line.splice(j, 1);
chunk = line[j].replace(/[\s]*$/g, "");
}
if (j < line.length)
{
line[i] += ',' + line[j];
line.splice(j, 1);
}
}
}
for (var i = 0; i < line.length; i++)
{
// remove leading/trailing whitespace
line[i] = line[i].replace(/^[\s]*|[\s]*$/g, "");
// remove leading/trailing quotes
if (line[i].charAt(0) == '"') line[i] = line[i].replace(/^"|"$/g, "");
else if (line[i].charAt(0) == "'") line[i] = line[i].replace(/^'|'$/g, "");
}
return line;
}
function csvToJson ()
{
var message = "";
var error = false;
var f = document.forms["convertForm"];
var csvText = f.elements["csv"].value;
var jsonText = "";
setMessage(message, error);
if (csvText == "") { error = true; message = "Enter CSV text below."; }
if (!error)
{
benchmarkStart = new Date();
csvRows = csvText.split(/[\r\n]/g); // split into rows
// get rid of empty rows
for (var i = 0; i < csvRows.length; i++)
{
if (csvRows[i].replace(/^[\s]*|[\s]*$/g, '') == "")
{
csvRows.splice(i, 1);
i--;
}
}
if (csvRows.length < 2) { error = true; message = "The CSV text MUST have a header row!"; }
else
{
objArr = [];
for (var i = 0; i < csvRows.length; i++)
{
csvRows[i] = parseCSVLine(csvRows[i]);
}
benchmarkParseEnd = new Date();
for (var i = 1; i < csvRows.length; i++)
{
if (csvRows[i].length > 0) objArr.push({});
for (var j = 0; j < csvRows[i].length; j++)
{
objArr[i - 1][csvRows[0][j]] = csvRows[i][j];
}
}
benchmarkObjEnd = new Date();
jsonText = JSON.stringify(objArr, null, "\t");
benchmarkJsonEnd = new Date();
f.elements["json"].value = jsonText;
benchmarkPopulateEnd = new Date();
message = getBenchmarkResults();
}
}
setMessage(message, error);
}
$(document).ready(function(){
$('#submitButton').on('click', function(){
console.log('i got here');
csvToJson;
});
});
This works perfectly but console.log is never shown.
And if I try to do something like return the jsonText from the csvToJson function and then append it to the second textarea, that doesn't work either.
function csvToJson ()
{
//same code here
return jsonText;
}
$(document).ready(function(){
$('#submitButton').on('click', function(){
console.log('i got here');
jsont = csvToJson();
$("#json").val(jsonT);
});
It's clearly something I don't get about submitting. Should I use jquery .submit() function ?
You are missing brackets when calling csvToJson inside the click handler.
Change:
$('#submitButton').on('click', function(){
csvToJson;
});
TO
$('#submitButton').on('click', function(){
csvToJson();
});
DEMO: http://jsfiddle.net/MRmJM/1/
One note: If CSV is separated by semi-colon (not uncommon) , parser code fails to create proper object

checking for duplicate file while uploading multiple file in Javascript

I used the below code to upload multiple files. Its working absolutely fine but as i need to check that the file which i am uploading is duplicate or not, i am facing one problem in that. I created one function called checkDuplicate for that and calling it inside the function. But the problem is that the for loop is looping double the size of the array. I don't know why it is so. Please kindly help me if anyone has any idea.
Here is the Javascript
<script type="text/javascript">
function MultiSelector(list_target, max) {
this.list_target = list_target;
this.count = 0;
this.id = 0;
if (max) {
this.max = max;
} else {
this.max = -1;
};
this.addElement = function(element) {
if (element.tagName == 'INPUT' && element.type == 'file') {
element.name = 'file_' + this.id++;
element.multi_selector = this;
element.onchange = function() {
var new_element = document.createElement('input');
new_element.type = 'file';
this.parentNode.insertBefore(new_element, this);
this.multi_selector.addElement(new_element);
this.multi_selector.addListRow(this);
this.style.position = 'absolute';
this.style.left = '-1000px';
};
if (this.max != -1 && this.count >= this.max) {
element.disabled = true;
}
;
this.count++;
this.current_element = element;
}
else {
alert('Error: not a file input element');
}
;
};
this.addListRow = function(element) {
var new_row = document.createElement('div');
var new_row_button = document.createElement('img');
new_row_button.setAttribute("src","<%=request.getContextPath()%>/images/deletei.gif");
new_row_button.onclick = function() {
this.parentNode.element.parentNode.removeChild(this.parentNode.element);
this.parentNode.parentNode.removeChild(this.parentNode);
this.parentNode.element.multi_selector.count--;
this.parentNode.element.multi_selector.current_element.disabled = false;
return false;
};
if(checkDuplicate(element)) {
new_row.element = element;
new_row.innerHTML = element.value + " ";
new_row.appendChild(new_row_button);
this.list_target.appendChild(new_row);
}
};
};
function checkDuplicate(element) {
var arr = new Array();
var i = 0,dup=0;
//alert(new_row.element = element.value);
if(dup==0) {
arr[i++] = element.value;
dup=1;
}
alert("Length ==> "+ arr.length);
for ( var j = 0; j < arr.length; j++) {
alert("Name ==> " + arr[j]);
if(arr[j] == element.value && j>=1) {
alert("Duplicate");
} else {
alert("Not Duplicate");
arr[i++] = element.value;
}
}
}
</script>
Here is the HTML
<body>
<!-- This is the form -->
<form enctype="multipart/form-data" action=""method="post">
<input id="my_file_element" type="file" name="file_1">
<input type="submit">
<br/>
<br/>
Files:
<!-- This is where the output will appear -->
<div id="files_list"></div>
</form>
<script>
var multi_selector = new MultiSelector(document
.getElementById('files_list'), 15);
multi_selector.addElement(document.getElementById('my_file_element'));
</script>
</body>
</html>
because you have the arr[i++] = element.value; in the last line, and j < arr.length in the for, so every time the array.lenght gets bigger and bigger.
change the for line to these two lines:
var len = arr.length;
for ( var j = 0; j < len; j++) {

Categories