checking for duplicate file while uploading multiple file in Javascript - 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++) {

Related

How do i restrict the user add duplicates and specific file format

How can I achieve gmail style of file uploading. From the below code i can select multiple file and am displaying selected files with anchor tag. How can i avoid duplicate files and adding and How to restrict the user to select only pdf and doc file? i need to alert if user select duplicate or if user select other than doc or pdf
<div class="container">
<form id="fileupload" action="#" method="POST" enctype="multipart/form-data">
<div class="row files" id="files1">
<h2>Files 1</h2>
Browse <input type="file" name="files1" multiple />
<br />
<ul class="fileList"></ul>
</div>
</form>
</div>
var filesToUpload = [];
var output = [];
$.fn.fileUploader = function (filesToUpload) {
this.closest(".files").change(function (evt) {
for (var i = 0; i < evt.target.files.length; i++) {
var found = false;
for(var j = 0; j < filesToUpload.length; j++){
if(evt.target.files[i].name == filesToUpload[j].name){
found = true;
break;
}
}
if(found == false){
filesToUpload.push(evt.target.files[i]);
}
else{
alert("duplicate");
}
}
for (var i = 0; i < evt.target.files.length; i++) {
var file= evt.target.files[i];
var found = false;
for(var j = 0; j < filesToUpload.length; j++){
if(evt.target.files[i].name == filesToUpload[j].name){
found = true;
break;
}
}
if(found == false){
var removeLink = "<a class=\"removeFile\" href=\"#\" data-fileid=\"" + i + "\">X</a>";
output.push("&nbsp&nbsp&nbsp<li><strong>",file.name,"</strong>&nbsp",removeLink,"</li> ");
}
else{
alert("duplicate");
}
}
$(this).children(".fileList").append(output.join(""));
});
};
$(document).on("click",".removeFile", function(e){
e.preventDefault();
var fileName = $(this).parent().children("strong").text();
// loop through the files array and check if the name of that file matches FileName
// and get the index of the match
for(i = 0; i < filesToUpload.length; ++ i){
if(filesToUpload[i].name == fileName){
//console.log("match at: " + i);
// remove the one element at the index where we get a match
filesToUpload.splice(i, 1);
}
}
//console.log(filesToUpload);
// remove the <li> element of the removed file from the page DOM
$(this).parent().remove();
});
$("#files1").fileUploader(filesToUpload);
$("#files2").fileUploader(filesToUpload);
$("#uploadBtn").click(function (e) {
e.preventDefault();
});
$.fn.fileUploader = function(filesToUpload) {
this.closest(".files").change(function(evt) {
var index;
for (var i = 0; i < evt.target.files.length; i++) {
index = filesToUpload.indexOf(evt.target.files[i]);
if (index > -1) {
filesToUpload.splice(index, 1);
}
}
for (i = 0; i < evt.target.files.length; i++) {
var filename = evt.target.files[i].name;
var valid_extensions = /(\.pdf|\.doc|\.docx)$/i;
if (valid_extensions.test(filename)) {
for (var i = 0; i < evt.target.files.length; i++) {
filesToUpload.push(evt.target.files[i]);
};
var output = [];
for (var i = 0, f; f = evt.target.files[i]; i++) {
var removeLink = "<a class=\"removeFile\" href=\"#\" data-fileid=\""+ i + "\">Remove</a>";
output.push("<li><strong>", escape(f.name),"</strong> - ", removeLink,"</li> ");
}
$(this).children(".fileList").append(output.join(""));
} else {
alert('Invalid File');
return false;
}
}
});
};
var filesToUpload = [];
$(document).on("click", ".removeFile", function(e) {
e.preventDefault();
var fileName = $(this).parent().children("strong").text();
// loop through the files array and check if the name of that file matches
// FileName
// and get the index of the match
for (i = 0; i < filesToUpload.length; ++i) {
if (filesToUpload[i].name == fileName) {
// console.log("match at: " + i);
// remove the one element at the index where we get a match
filesToUpload.splice(i, 1);
}
}
// console.log(filesToUpload);
// remove the <li> element of the removed file from the page DOM
$(this).parent().remove();
});
$("#files1").fileUploader(filesToUpload);
$("#files2").fileUploader(filesToUpload);
$("#uploadBtn").click(function(e) {
e.preventDefault();
});

Why is my elseif statement running everytime

I am building a form sending function in JavaScript, and I have run into a problem where it executes an else if statement every time. Here is my script:
this.submit = function() {
var url = this.url + "?";
for(el in this.elements) {
var e = $(this.elements[el]);
var n = this.names[el];
if(n === "submit")
{
window.alert("submit");
}
else
{
url += n + "=";
}
if(el == "#dropdown")
{
var options = e.children();
for(var i = 0; i < options.length; i++) {
var option = $('#' + options[i].id);
if(option.attr('selected'))
{
url += option.attr('name');
url += "&";
window.alert("dropdown worked");
break;
}
}
}
else if(el != "#submit") {
url += e.attr('value');
url += "&";
window.alert("input worked");
}
}
window.location.href = url;
};
The problem being that the else if(el != "#submit"){} runs even when the id in question is "#submit". Does anyone know why this doesn't work?
To help, here is my php document, and the rest of the form constructer:
php:
<!DOCTYPE html>
<html>
<head>
<title>Test</title>
<script src="http://code.jquery.com/jquery-1.10.2.js"></script>
</head>
<body>
<?php if(!$_GET): ?>
<form id="form1">
<input type="text" id="input1" name="name"/>
<br>
<select id="dropdown" name="color">
<option id="null" name="null"></option>
<option id="opt1" name="blue">blue</option>
<option id="opt2" name="yellow">yellow</option>
</select>
<br>
<button type="submit" id="submit" name="submit"onclick="form1.submit()">Submit data</button>
</form>
<script src="http://charlie/form.js"></script>
<script>
var form1 = new form("form1");
form1.setElements();
form1.logElements();
</script>
<?php elseif(!(isset($_GET['name']) || isset($_GET['color']))): ?>
<p style="color:red">ERROR! form.js failed</p>
<?php else: ?>
<p><?= $_GET['name'] ?></p>
<p><?= $_GET['color'] ?></p>
<?php endif; ?>
</body>
</html>
form constructer:
function form(id) {
this.id = "#" + id;
this.url = window.location.href;
this.elements = [];
this.names = [];
this.setElements = function() {
var elements = [],names = [],children = $(this.id).children();
for(var i = 0; i < children.length; i++) {
var childid = children[i].id;
if(childid)
{
elements.push('#' + childid);
}
}
this.elements = elements;
for(var e in this.elements) {
names.push($(this.elements[e]).attr('name'));
}
this.names = names;
};
this.logElements = function() {
for(var e in this.elements) {
console.log(this.elements[e]);
}
for(var n in this.names) {
console.log(this.names[n]);
}
};
this.submit = function() {
var url = this.url + "?";
for(el in this.elements) {
var e = $(this.elements[el]);
var n = this.names[el];
if(n === "submit")
{
window.alert("submit");
}
else
{
url += n + "=";
}
if(el == "#dropdown")
{
var options = e.children();
for(var i = 0; i < options.length; i++) {
var option = $('#' + options[i].id);
if(option.attr('selected'))
{
url += option.attr('name');
url += "&";
window.alert("dropdown worked");
break;
}
}
}
else if(el != "#submit") {
url += e.attr('value');
url += "&";
window.alert("input worked");
}
}
window.location.href = url;
};
}
Turning my comment into an answer with some code. The "in" operator in Javascript iterates over properties not the elements at each index. To make your current code work, change the code to the following:
var el;
var elementCount = this.elements.length;
for (var i = 0; i < elementCount; i++) {
el = this.elements[i];
This will produce the expected behavior.
The for...in loop is the cause. el tkaes the values 0, 1, 2 ...you need to compare this.elements[el] instead of el :
if(this.elements[el] == "#dropdown") ...
else if(this.elements[el] != "#submit") {
...

less than or equal to condition is not working in my script

<script type="text/javascript">
function ValidateAddOnModule(source, args) {
var gdv = document.getElementById('ContentPlaceHolder1_MainContent_grdAddonModules');
var j = 0;
var k = 0;
for (var i = 1; i <= gdv.rows.length - 1; i++) {
var img = document.getElementById('ContentPlaceHolder1_MainContent_grdAddonModules_ImgLanUserError_' + j);
var LANUser = document.getElementById('ContentPlaceHolder1_MainContent_grdAddonModules_txtAdditionalLANUser_' + j).value;
var MinLANUser = gdv.rows(i).cells(2).innerText;
// alert(MinLANUser);
// alert(LANUser);
if (MinLANUser != " ")
{
if (MinLANUser <= LANUser) {
alert("true");
img.style.visibility = "hidden";
}
else {
alert("false");
img.style.visibility = "visible";
k = 1;
}
j++;
}
}
if (k = 1) {
return false;
} else
{
return true;
}
}
</script>
frist try to change the numbers you grab from thext fields with parseInt() function
element.innerText will give you the output in string format. You have to first convert that value to integer using parseInt. Then only you can operate arithmetic operators on them.
var LANUser = document.getElementById('ContentPlaceHolder1_MainContent_grdAddonModules_txtAdditionalLANUser_' + j).value;
var MinLANUser = gdv.rows(i).cells(2).innerText;
convert these to integer type.
var LANUser = parseInt(document.getElementById('ContentPlaceHolder1_MainContent_grdAddonModules_txtAdditionalLANUser_' + j).value);
var MinLANUser = parseInt(gdv.rows(i).cells(2).innerText);

Input Button onclick event not firing

I'm fairly new to JavaScript and trying to build a simple photoviewer, slideshow application. I probably have errors/wrong practices in code that I don't know about yet. The event on slideshow button fires and I can see the output in the console, however the event on the random slide show button does not fire.
HTML5 snippet
<form>
<div id="controls">
<input type="button" id="slideshow" value="Slide Show" />
<input type="button" id="randomSlideshow" value="Random Slide Show" />
</div>
</form>
<script src="js/PhotoViewer.js"></script>
</body>
JS snippet
var photosArrayGlobal = new Array();
var photoIndexGlobal = 0;
var displayGlobal;
window.onload = main;
function main() {
"use strict";
document.getElementById("slideshow").onclick = getArrayPhotosNames;
document.getElementById("randomSlideshow").onclick = randomize(photosArrayGlobal);
displayGlobal = document.getElementById("myImage");
document.getElementById("nextSlide").onclick = function () {
displayGlobal.setAttribute("src", photosArrayGlobal[1]); //Test value, image 2
};
}
function getArrayPhotosNames() {
var folderName = document.getElementById("photoFolder").value;
var commonName = document.getElementById("commonName").value;
var startNum = document.getElementById("startNum").value;
var endNum = document.getElementById("endNum").value;
var j = 0;
if (startNum > endNum) {
alert("Invalid Numbers");
}
var nameArray = new Array();
for (var i = startNum; i <= endNum; i++) {
nameArray[j] = folderName + commonName + i + ".jpg";
j++;
}
photosArrayGlobal = nameArray.slice();
console.log(photosArrayGlobal);
return nameArray;
}
function randomize(dataArray) {
var i = dataArray.length;
var j, tempi, tempj;
if (i === 0) {
return false;
}
while (--i) {
j = Math.floor(Math.random() * (i + 1));
tempi = dataArray[i];
tempj = dataArray[j];
dataArray[i] = tempj;
dataArray[j] = tempi;
}
console.log(dataArray);
}
The onclick handler is expecting a function, but you're passing it the value returned from the randomize() function (which happens to be undefined). Change it to the following:
document.getElementById("randomSlideshow").onclick = function() {
randomize(photosArrayGlobal);
};

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

Categories