given this html snippet
<div id="imageSelection" class="form-group">
#Html.LabelFor(m => m.PostedFiles,"Select images/videos" ,new {id="fileSelect",#for="fileElem", #class="form-control btn btn-sm btn-success", style="width:144px;" })
#Html.TextBoxFor(m => m.PostedFiles, new
{
type = "file",
id = "fileElem",
#class = "col-md-10 form-control",
style="display:none;",
multiple = "multiple",
accept = "image/*",
onchange = "handleFiles(this.files)"
})
</div>
which works fine, you click the button, the file picker opens, you select some files and click the button to close the file picker. The onchange event is not firing (onchange is the event suggested by the example here)
It generates this html in the page
<div id="imageSelection" class="form-group">
<label class="form-control btn btn-sm btn-success" for="fileElem" id="fileSelect" style="width:144px;">Select images/videos</label>
<input accept="image/*" class="col-md-10 form-control" id="fileElem" multiple="multiple" name="PostedFiles" onchange="handleFiles(this.files)" style="display:none;" type="file" value="" />
</div>
Here is the script
<script>
$(document)
.ready(function () {
//element variables for the thumbnail display
var dropbox = $("#dropbox"),
filePropertyDisplay = $("#loadingImageFileProperties"),
fileName = $("#dd_filename"),
fileSize = $("#dd_filesize"),
fileType = $("#dd_filetype"),
gallery = $("#imageGallery"),
uploading = $("#imageUploading"),
fileSelect = document.getElementById("fileSelect"), //$("#fileSelect"),
fileElem = document.getElementById("fileElem"), //$("#fileElem"),
messages = $("#messageArea");
gallery.hide();
uploading.hide();
//add event listeners to handle events
dropbox.on("dragenter", function(e) {
e.stopPropagation();
e.preventDefault();
});
dropbox.on("dragover", function (e) {
e.stopPropagation();
e.preventDefault();
});
dropbox.on("drop", function (e) {
e.stopPropagation();
e.preventDefault();
var dt = e.originalEvent.dataTransfer;
var files = dt.files;
handleFiles(files);
});
fileSelect.addEventListener("click", function (e) {
if (fileElem) {
fileElem.click();
}
e.preventDefault(); // prevent navigation to "#"
}, false);
//fileSelect.on("click", function (e) {
// if (fileElem) {
// fileElem.click();
// }
// // prevent navigation to "#"
// e.preventDefault();
//});
function handleFiles(files) {
alert(files.length);
}
});
</script>
I originally was trying to stick with JQuery but couldn't get that to work with .on() either, so i reverted back to Javascript, per the example, but that doesn't work either.
The drop functionality works, and calls handleFiles but the fileElem onchange method doesn't fire.
EDIT:
Sorry that made me realize that the problem was reading the files you've selected instead of just getting the code to work.
I've just added:
var files = $(this)[0].files;
To get the files collection the user selected (it could be one or more);
and then:
for (var i = 0; i < files.length; i++) {
alert(files[i].name);
}
loop through all the files selected and just get the name of it. You can also read .size if you need to.
This will the proper way to handle what you are trying to achieve.
$(document)
.ready(function () {
//element variables for the thumbnail display
var dropbox = $("#dropbox"),
filePropertyDisplay = $("#loadingImageFileProperties"),
fileName = $("#dd_filename"),
fileSize = $("#dd_filesize"),
fileType = $("#dd_filetype"),
gallery = $("#imageGallery"),
uploading = $("#imageUploading"),
fileSelect = document.getElementById("fileSelect"), //$("#fileSelect"),
fileElem = document.getElementById("fileElem"), //$("#fileElem"),
messages = $("#messageArea");
gallery.hide();
uploading.hide();
//add event listeners to handle events
dropbox.on("dragenter", function(e) {
e.stopPropagation();
e.preventDefault();
});
dropbox.on("dragover", function (e) {
e.stopPropagation();
e.preventDefault();
});
dropbox.on("drop", function (e) {
e.stopPropagation();
e.preventDefault();
var dt = e.originalEvent.dataTransfer;
var files = dt.files;
handleFiles(files);
});
fileSelect.addEventListener("click", function (e) {
if (fileElem) {
fileElem.click();
}
e.preventDefault(); // prevent navigation to "#"
}, false);
$('#fileElem').on('change',function(e){
var files = $(this)[0].files;
for (var i = 0; i < files.length; i++) {
alert(files[i].name);
//alert(files[i].size);
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id="imageSelection" class="form-group">
<label for="fileElem" class="form-control btn btn-sm btn-success", style="width:144px;" id="fileSelect">Select images/videos</label>
<input type="file" id = "fileElem" class = "col-md-10 form-control"
style="display:none;"
multiple = "multiple"
accept = "image/*"
</div>
Related
I want to append an li when the enter key is pressed using keydown. However, when I press the enter key the new li appears momentarily and then disappear.
How can I make it save the change or how can I fix the code?
var submitBtn = document.querySelector("input[type = 'submit'");
var enterTodo = document.querySelector("input[type = 'text']");
var todoList = document.querySelector("#todoList");
enterTodo.addEventListener('keydown', (event)=>{
if(event.which == 13){
var todo = enterTodo.value;
todoList.append("<li>" + todo + "</li>");
};
})
The reason why it was showing up and dissapearing almost immediately is because forms automatically refresh the page on submit. Which is why you have to use preventDefault in the onSubmit event.
I set up two working samples based on your code. In both, I went ahead and got your code to to append the proper li elements rather than the text `<li>${todo}</li>` to the todoList. I also made the enterTodo clear after being added to the list.
This uses the code about how you had it with the event listener on keydown, but it prevents the refresh.
var submitBtn = document.querySelector("input[type = 'submit'");
var enterTodo = document.querySelector("input[type = 'text']");
var todoList = document.querySelector("#todoList");
var form = document.querySelector("form");
form.onsubmit = (evt) => evt.preventDefault();
function addTodo() {
var todo = enterTodo.value;
var li = document.createElement('li');
li.textContent = todo;
todoList.appendChild(li);
enterTodo.value = "";
}
enterTodo.addEventListener('keydown', (event) => {
if (event.which == 13) {
addTodo();
};
})
<body>
<form>
<input type="text" onsubmit="" />
<input type="submit" />
<ul id="todoList"></ul>
</form>
</body>
This uses the from's onSubmit handler to perform the addition to the todoList instead of directly handling the enter key in the text input. This has the added benefit of also supporting the submit button click as well.
var submitBtn = document.querySelector("input[type = 'submit'");
var enterTodo = document.querySelector("input[type = 'text']");
var todoList = document.querySelector("#todoList");
var form = document.querySelector("form");
function addTodo() {
var todo = enterTodo.value;
var li = document.createElement('li');
li.textContent = todo;
todoList.appendChild(li);
enterTodo.value='';
}
form.onsubmit = (evt) => {evt.preventDefault();
addTodo();
}
<body>
<form>
<input type="text" onsubmit="" />
<input type="submit" />
<ul id="todoList"></ul>
</form>
</body>
I have a number of textareas and when I click on a paragraph outside the text is supposed to be added to the textarea, it works but the text is also getting added to the textareas above.
I'm a bit stumped on why this is happening and as I have 10 textaraes so clicking a paragraph at the bottom of the page adds the text to all the other textareas above.
Javascript
$(document).ready(function () {
$("#PollutionPreventionDivScrollDisplay").hide();
$("#PollutionPreventionDivScroll").on("click", function () {
$("#PollutionPreventionDivScrollDisplay").toggle();
});
var cartlist = document.querySelector("#EnvironmentalActionPollutionPreventionIdeasForAction");
var items = document.querySelectorAll("[data-item]");
[].forEach.call(items, function (item) {
item.addEventListener("click", function (e) {
e.preventDefault();
cartlist.value += `\n${item.innerHTML}`;
});
});
});
$(document).ready(function () {
$("#WasteDivScrollDisplay").hide();
$("#WasteDivScrollDisplayScroll").on("click", function () {
$("#WasteDivScrollDisplay").toggle();
});
var cartlistOne = document.querySelector("#EnvironmentalActionWasteManagementIdeasForAction");
var itemsOne = document.querySelectorAll("[data-item]");
[].forEach.call(itemsOne,
function (itemOne) {
itemOne.addEventListener("click", function (e) {
e.preventDefault();
cartlistOne.value += `\n${itemOne.innerHTML}`;
});
});
});
$(document).ready(function () {
$("#EnergyDivScrollDisplay").hide();
$("#EnergyDivScrollDisplayScroll").on("click", function () {
$("#EnergyDivScrollDisplay").toggle();
});
var cartlistTwo = document.querySelector("#EnvironmentalActionEnergyIdeasForAction");
var itemsTwo = document.querySelectorAll("[data-item]");
[].forEach.call(itemsTwo,
function (itemTwo) {
itemTwo.addEventListener("click", function (c) {
c.preventDefault();
cartlistTwo.value += `\n${itemTwo.innerHTML}`;
});
});
});
Example of html
<div class="row">
<div id="PollutionPreventionDivScrollDisplay" class="col-md-12 border-colour fixed-height">
#foreach (var info in Model.EnvironmentalActionPollutionPreventionExtraInfo)
{
var countItems = counter++;
<p><a data-item="#countItems" href="#">#info</a></p>
}
</div>
</div>
<div class="col-md-4 border-colour-right">
<div class="form-group">
<span class="mouse-pointer text-danger" id="PollutionPreventionDivScroll">Click to add options</span>
<label class="sr-only" for="EnvironmentalActionPollutionPreventionIdeasForActionPlaceholder">Environmental Action Pollution Prevention Ideas For Action</label>
#Html.TextAreaFor(x => x.EnvironmentalActionPollutionPreventionIdeasForAction, new { Class = "form-control", Placeholder = Model.EnvironmentalActionPollutionPreventionIdeasForActionPlaceholder, rows = "8" })
</div>
</div>
All other code is the same except the sames are different
Ok silly mistake, I had all 'data-item' the same should have been 'data-item-one', 'data-item-two' etc
I have found a code on internet to upload multiple images. While you select the image, it will show the selected image just below as preview, now the problem is what if I selected the wrong image and I want to remove that particular image, also no more than 4 image should be allowed
hope you get what I want to say below is the code
<input type="file" multiple id="gallery-photo-add">
<div class="gallery"></div>
and jquery for the code is
$(function() {
// Multiple images preview in browser
var imagesPreview = function(input, placeToInsertImagePreview) {
if (input.files) {
var filesAmount = input.files.length;
for (i = 0; i < filesAmount; i++) {
var reader = new FileReader();
reader.onload = function(event) {
$($.parseHTML('<img>')).attr('src', event.target.result).appendTo(placeToInsertImagePreview);
}
reader.readAsDataURL(input.files[i]);
}
}
};
$('#gallery-photo-add').on('change', function() {
imagesPreview(this, 'div.gallery');
});
});
The file list of HTML5 file input is readonly. So it's not possible to remove a single file out from a multiple file selection.
It's perfectly fine to empty a file input by resetting the form. You just can't modify it. So if you use 4 seperate single file selections, it's a simple matter of clearing the one that's being removed by the user:
HTML:
<form>
<input type="file" name='images[]' class="gallery-photo-add" id='image1' />
<input type="file" name='images[]' class="gallery-photo-add" id='image2' />
<input type="file" name='images[]' class="gallery-photo-add" id='image3' />
<input type="file" name='images[]' class="gallery-photo-add" id='image4' />
</form>
<div class="gallery"></div>
JS:
$(function() {
// Multiple images preview in browser
var imagesPreview = function(placeToInsertImagePreview) {
// Empty preview so we can safely rebuild it
$(placeToInsertImagePreview).empty();
// Get all files
var elems = document.getElementsByClassName("gallery-photo-add");
// Loop through each file and append them to the preview if available
for (i = 0; i < elems.length; i++) {
if (elems[i].files.length != 0) {
var reader = new FileReader();
var id = $(elems[i]).attr('id');
reader.onload = (function(id) {
return function(e){
$($.parseHTML('<img>')).attr({
'src' : e.target.result,
'data-id' : id
}).appendTo(placeToInsertImagePreview);
}
})(id);
reader.readAsDataURL(elems[i].files[0]);
}
}
};
// Temporarely wrap a form element around the input to reset it
window.reset = function(e) {
e.wrap("<form>").closest('form').get(0).reset();
e.unwrap();
}
$('div.gallery').on('click', 'img', function() {
var id = $(this).attr("data-id");
reset($('#'+id));
$(this).remove();
});
$('.gallery-photo-add').on('change', function() {
imagesPreview('div.gallery');
});
});
You can test it here: https://jsfiddle.net/81nytqsc/2/
$('div.gallery').on('click','img',function(){
var files= $('#gallery-photo-add).get(0).files;
for(i=0;i<files.length;i++){
if(files[i]==$(this).attr('src')){
files= jQuery.grep(files, function(value) {
return value != files[i];
}
}
}
$(this).remove();
});
My task is i have added multiple browse file clicking on add more button at the same time i have to view the file also after browsing the file for this i have used below code and i have succeded to browse the file on one browse box but i was unable to view all the image simultaneously.I am not getting how to do this
my check.html file
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>
<script src="custom.js" type="text/javascript"></script>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"></script>
<div class="file_wrapper" id="file_wrapper">
<div>
<span class="btn btn-default btn-file"><i class="fa fa-upload"></i>
Select Image<input id="fileupload" class="fileupload" type="file" name="userFiles[]" required/>
</span>
<span class="btn btn-success">
<a href="javascript:void(0);" class="add_image" title="Add field">
<span class="glyphicon glyphicon-plus" >Add more</span>
</a>
</span>
</div>
</div>
<hr />
<b>Live Preview</b>
<br />
<br />
<div id="dvPreview">
</div>
my second custom.js file is
// Add More field script
$(document).ready(function(){
var maxField = 10; //Input fields increment limitation
var addButton = $('.add_image'); //Add button selector
var wrapper = $('.file_wrapper'); //Input field wrapper
var fieldHTML = '<div><span class="btn btn-default btn-file"><i class="fa fa-upload"></i>Select Image<input id="fileupload" class="fileupload" type="file" name="userFiles[]" required/></span> <span class="btn btn-success"><span class="glyphicon glyphicon-minus">Remove</span></span></div>';
var x = 1; //Initial field counter is 1
$(addButton).click(function(){ //Once add button is clicked
if(x < maxField){ //Check maximum number of input fields
x++; //Increment field counter
$(wrapper).append(fieldHTML); // Add field html
}
});
$(wrapper).on('click', '.remove_button', function(e){ //Once remove button is clicked
e.preventDefault();
$(this).parent('div').remove(); //Remove field html
x--; //Decrement field counter
});
});
$(function () {
// View Image on Browse Script
$(".fileupload").change(function () {
if (typeof (FileReader) != "undefined") {
var dvPreview = $("#dvPreview");
dvPreview.html("");
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.jpg|.jpeg|.gif|.png|.bmp)$/;
$($(this)[0].files).each(function () {
var file = $(this);
if (regex.test(file[0].name.toLowerCase())) {
var reader = new FileReader();
reader.onload = function (e) {
var img = $("<img />");
img.attr("style", "height:200px;width: 300px");
img.attr("src", e.target.result);
dvPreview.append(img);
}
reader.readAsDataURL(file[0]);
} else {
alert(file[0].name + " is not a valid image file.");
dvPreview.html("");
return false;
}
});
} else {
alert("This browser does not support HTML5 FileReader.");
}
});
});
Please help me
Thanks in Advance
every time you choose new image you remove previous one so delete first dvPreview.html("");
// Add More field script
$(document).ready(function(){
var maxField = 10; //Input fields increment limitation
var addButton = $('.add_image'); //Add button selector
var wrapper = $('.file_wrapper'); //Input field wrapper
var fieldHTML = '<div><span class="btn btn-default btn-file"><i class="fa fa-upload"></i>Select Image<input id="fileupload" class="fileupload" type="file" name="userFiles[]" required/></span> <span class="btn btn-success"><span class="glyphicon glyphicon-minus">Remove</span></span></div>';
var x = 1; //Initial field counter is 1
$(addButton).click(function(){ //Once add button is clicked
if(x < maxField){ //Check maximum number of input fields
x++; //Increment field counter
$(wrapper).append(fieldHTML); // Add field html
}
});
$(wrapper).on('click', '.remove_button', function(e){ //Once remove button is clicked
e.preventDefault();
$(this).parent('div').remove(); //Remove field html
x--; //Decrement field counter
});
});
$(function () {
// View Image on Browse Script
$(".fileupload").change(function () {
if (typeof (FileReader) != "undefined") {
var dvPreview = $("#dvPreview");
//dvPreview.html("");
var regex = /^([a-zA-Z0-9\s_\\.\-:])+(.jpg|.jpeg|.gif|.png|.bmp)$/;
$($(this)[0].files).each(function () {
var file = $(this);
if (regex.test(file[0].name.toLowerCase())) {
var reader = new FileReader();
reader.onload = function (e) {
var img = $("<img />");
img.attr("style", "height:200px;width: 300px");
img.attr("src", e.target.result);
dvPreview.append(img);
}
reader.readAsDataURL(file[0]);
} else {
alert(file[0].name + " is not a valid image file.");
//dvPreview.html("");
return false;
}
});
} else {
alert("This browser does not support HTML5 FileReader.");
}
});
});
I have problem with uploading files in my existing form.
What I am looking for is script that will make possible to add multiple files (max 5) and you can add at once from one to five files. If you add one by one, I need it to add new, not replace the previous one.
I got form looking like this:
Name
LastName
Email
Phone number
Interests
Files
and filenames are created like this: name+lastname+phonenumber+filename
And I add entry to database with path of everyfile - this is done and I need only good drag and drop zone.
I need it to show added filename and make it possible to delete added file from queue.
But I don't want files to upload when I add them. I want it to upload when I submit my whole form so filename can be created and path to DB can be added.
Could anyone please provide me good script to that, or based on my scripts from two topics I mentioned before make it avaiable to do what I want?
I was able to add 5 files one by one and I described it here:
HTML Add multiple file to the input
Also I was able to add more at once what I described here:
https://stackoverflow.com/questions/30499388/dropzone-js-into-another-form
I think that this example help you.
This app allow drag and drop files to gray zone (1 or 5)
If you click on the file name, it removes file from the list.
function init() {
//get dragdrop element
var dd = document.getElementById("dragdrop");
//get files element
$files = document.getElementById("files");
dd.ondragover = stop;
dd.ondragleave = stop;
if ('FileReader' in window) {
document.ondrop = dragAccept;
}
//get form
var $form = document.querySelector("form");
//catch on submit
$form.onsubmit = function (e) {
stop(e);
var fd = new FormData();
//apend files to FormData
for (var i in files){
var file = files[i].file;
var filename = file.name;
var name = "file";
fd.append(name, file, filename);
};
//append inputs to FormData
var $inputs = $form.querySelectorAll("input");
for (var i = 0; i < $inputs.length; i++) {
var $input = $inputs[i];
fd.append($input.getAttribute("name"), $input.value);
}
//Send data
var xhr = new XMLHttpRequest();
xhr.open('POST', '/echo/html/', true);
xhr.send(fd)
}
}
function stop(e) {
e.stopPropagation();
e.preventDefault();
}
function dragAccept(e) {
stop(e);
if (e.dataTransfer.files.length > 0)
for (var i = 0; i < e.dataTransfer.files.length; i++) {
addFile(e.dataTransfer.files[i]);
}
}
//file list store
var files = {};
// html element of file list
var $files = null;
//add file to file list
function addFile(file) {
//add files with diferent name, max files count 5
if (!(file.name in files) && Object.keys(files).length < 5) {
var div = createFile(file.name);
$files.appendChild(div);
files[file.name] = {
file: file,
element: div
}
}
}
//create html element with file name
function createFile(name) {
var div = document.createElement("div");
div.innerText = name;
var input = document.createElement("input")
//remove on click
div.addEventListener("click", function () {
$files.removeChild(this);
delete files[name];
})
return div;
}
window.addEventListener("load", init);
<form method="post" enctype="multipart/form-data" action="">
<label>Name<input name="name" /></label>
<label>Last name<input name="lastName" /></label>
<label>Email<input name="email" /></label>
<div id="dragdrop" style="width: 300px; height: 300px; background-color:lightgray">Drag drop zone</div>
<div id="files"></div>
<button type="submit">Send</button>
</form>