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("   <li><strong>",file.name,"</strong> ",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();
});
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") {
...
No this isn't a duplicate because all of the answers are different in other posts.
Does anyone know how to get replace something specific in a string? for example I'm trying to get rid of ALL commas that area together. Keep single commas but get rid of two only
For example:
w,h,o,,w,h,a,t,w,h,e,n,w,h,e,r,e,,t,h,e,n,,c,a,n,,b,u,t,,
I want to get rid of all instances where the double commas appear. Something kind of like:
var example = text.replace(/,,/g,' '); /*Space where ' ' is*/
If you understand what I mean. The next step is:
var text.replace(/,/g,'');
Thank you!
Code:
<html>
<head>
<script>
function decrypt() {
var input = document.getElementById("input").value;
var x = input.split(",");
var txtDisp="";
for(var i = 0; i < x.length; i++) {
if(x[i].type = "text") {
crack = 94-(x[i]-32)+32;
toTxt = String.fromCharCode(this, crack);
txtDisp = txtDisp+","+toTxt;
prep = txtDisp.replace(/,,/g,"");
}
document.getElementById("prompt").innerHTML=prep;
}
}
</script>
</head>
<body>
<textarea rows='4' cols='100' style='resize:none;' id='input'></textarea>
<br>
<input type='button' value='execute' onclick='decrypt()' />
<p id='prompt'>
</p>
</body>
</html>
P.s. this code is already posted somewhere else where I asked a question.
Why don't you do:
var text = "61,59,44,47,43,43, ,39,54,37, ,37,47,41,44, ,59,61,48, ,53,48,42,47, ,42,54,57,53,44, ,47,56,42,57,48, ,47,56,56, ,43,61,53,58, ,47,41,44, ,42,39,61,43, ,43,53,48,59,57, ,42,54,57,44,57, ,61,48,58, ,39,47,41,50,58";
example = text.split(",,").join("").split(", ,").join("");
the result is:
"w,h,ow,h,a,t,w,h,e,n,w,h,e,r,et,h,e,nc,a,nb,u,t"
I myself also tried to do it like:
example = text.replace(/,,/g,'').replace(/, ,/g,'');
the result was:
"w,h,ow,h,a,t,w,h,e,n,w,h,e,r,et,h,e,nc,a,nb,u,t"
I changed your code like this:
function decrypt() {
var val = document.getElementById("input").value;
var x = val.split(",");
var txtDisp = "";
for (var i = 0; i < x.length; i++) {
if (!isNaN(parseInt(x[i]))) {
var num = parseInt(x[i]);
crack = 94 - (num - 32) + 32;
toTxt = String.fromCharCode(this, crack);
txtDisp = txtDisp + "," + toTxt;
prep = txtDisp.replace(/,,/g, "").replace(/, ,/g, "");
}
document.getElementById("prompt").innerHTML = prep;
}
}
and it works. check this DEMO out.
Try this:
function decrypt() {
var input = document.getElementById("input").value;
var x = input.split(",");
var txtDisp = "";
for (var i = 0; i < x.length; i++) {
if (x[i] !== ' ') {
crack = 94 - (x[i] - 32) + 32;
toTxt = String.fromCharCode(this, crack);
txtDisp += "," + toTxt;
} else {
txtDisp += " ";
}
}
document.getElementById("prompt").innerHTML = txtDisp.replace(/,/g, "");
}
I have a javascript which appends a string like 222222222222222 to another field (which will either be blank or already have numbers like 222222222222222 33333333333333) with a click of a button. Actually it's 15 digit IMEI of the phone. User has the option of submitting a single IMEI or bulk IMEI. When more then one IMEI is added to the bulk field by pressing the button from myVar1, the new IMEI gets inserted below the previous IMEI in the bulk field(myVar2).
Currently, I am using the below script to do this and it's working perfectly fine. The problem is that it doesn't check for duplicates before appending.
function append_myVar1_to_myVar2(){
var myVar1 = document.getElementById('myVar1_value').value;
var myVar2 = document.getElementById('myVar2_value').value;
if(document.getElementById('myVar2_value').value == ''){
document.getElementById('myVar2_value').value = myVar1;
}else{
document.getElementById('myVar2_value').value = document.getElementById('myVar2_value').value + "\r\n" + myVar1;
}
}
I have modified the script now as below (updated to include the first response, thanks to Brian) to check for duplicates, but it's not working. Request experts to have a look into it.
function append_myVar1_to_myVar2(){
var myVar1 = document.getElementById('myVar1_value').value;
var myVar2 = document.getElementById('myVar2_value').value;
if(document.getElementById('myVar2_value').value == ''){
document.getElementById('myVar2_value').value = myVar1;
}else{
var flag = 0;
var wordsarr = myVar2.split("\r\n");
for(var i = 0; i < wordsarr.length; i++)
{
if(wordsarr[i].value == myVar1)
{
flag = 1;
}
}
if(flag == 1)
{
alert('Value is duplicate.');
}
else{
document.getElementById('myVar2_value').value = document.getElementById('myVar2_value').value + "\r\n" + myVar1;
}
}}
Here is the html of the page:
<html>
<body>
<input id="myVar1_value" type="text" maxlength="15" name="myVar1_value">
<input id="IMEI_ADD" class="button_gray" type="button" onclick="append_myVar1_to_myVar2()" value="Add this IMEI to bulk entry" name="IMEI_ADD">
<p id="imei_bulk_field" class="form-row notes">
<textarea id="myVar2_value" class="input-text" rows="2" cols="5" placeholder="If you have more than one IMEI, insert them here by pressing the button above." name="myVar2_value"></textarea>
</p>
</body>
</html>
for(var i = 0; i < (myVar2.split("\r\n")).length; i++)
{
//here is wrong
if(myVar2[i].value == myVar1)
{
flag = 1;
}
You should change to
var wordsarr = myVar2.split("\n");
for(var i = 0; i < worsarr.length; i++)
{
if(wordsarr[i] == myVar1)
{
flag = 1;
}
}
if(flag == 1)
{
alert('Value is duplicate.');
}
Store splitted chunks ,and iterate over them:
var chunkArray = myVar2.split("\r\n");
for(var i = 0; i !== chunkArray.length; i++){
if(chunkArray[i] == myVar1){
flag = 1;
break;
}
}
var myVar2 = document.getElementById('myVar2_value').value;
Later...
if(myVar2[i].value == myVar1)
It looks like you are adding .value when you don't need to. Try:
if(myVar2[i] == myVar1)
This could be of assistance
function inArray(needle, haystack) {
var length = haystack.length;
for(var i = 0; i < length; i++) {
if(haystack[i] == needle) return true;
}
return false;
}
you could change the if with:
haystack[i].value == needle
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++) {