Find a dropzone to change attributes - javascript

I'm having some problems with the Dropzone.js. After I create a dropzone I want to change its values (for example the url) before sending the form via POST.
I already set the variable autoProcessQueue to false, so I can send the files when the form is sent.
Here is a test that I made but is not working...
var myDropzone = new Dropzone(me, {
url: uploadUrl
,maxFilesize: 10
,addRemoveLinks: true
,addDownloadLinks: true
,downloadFileUrl: downloadUrl
,autoProcessQueue: false
,init: function() {
var myDrop = this;
$("[id=btnSendMessage]").click(function(e){
// e.preventDefault();
url2 = '/file/upload/52175';
myDrop.url = url2;
myDrop.processQueue();
});
}
So, how can I change the url ? I dont know what to do here.
Thank you! :)

There is a page on the dropzone wiki that shows you how to do this. I'm typing it out here for posterity. You can take advantage of the processingfile event to set the upload url.
<form id="my-dropzone" action="/some-url" class="dropzone"></form>
<script>
Dropzone.options.myDropzone = {
init: function() {
this.on("processing", function(file) {
this.options.url = "/some-other-url";
});
}
};
</script>

Related

Redirect after form Submit (CSR)

Within a SharePoint form overriden by CSR (Client Side Rendering).
I tried adding a new button which does pretty much the same as the Save button except that it redirects to another form with given parameters.
The thing is, the redirection does not work.
I tried redirecting by changing the "action" property of the form but it doesn't seem to be taken in count.
Here is the new button :
<input id="custom_addLine" type="button" name="custom_addLine" value="+" class="ms-ButtonHeightWidth">
Here is the function called by the button and the addLine method following :
$('#custom_addLine').click(function(event){
event.preventDefault();
addLine(getQueryStringParameter('ID'));
});
function addLine(id) {
if(!PreSaveItem()) {
return false;
}
var actionUrl = "/Lists/PurchaseRequestLine/NewForm.aspx?PurchaseRequestID="+ id;
var encodedActionUrl = encodeURIComponent(actionUrl);
var newFormAction = location.pathname + '?Source=' + encodedActionUrl;
$('#aspnetForm').attr('action',newFormAction);
if(SPClientForms.ClientFormManager.SubmitClientForm('WPQ1')){
return false;
}
WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions('custom_addLine', "", true, "", "", false, true));
}
getQueryStringParameter is a custom made function to retrieve parameters from URI (which works).
The tricky part is that I want to preserve the default action URI in case the original Save button is clicked on, which is why action parameter is modified on the fly.
You can change the Source attribute directly from the original action:
function addLine(id) {
if(!PreSaveItem()) {
return false;
}
var oldActionUrl = $('#aspnetForm').attr('action');
var oldSource = GetUrlKeyValue("Source", true, oldActionUrl);
var newSource = "/Lists/PurchaseRequestLine/NewForm.aspx?PurchaseRequestID="+ id;
var newActionUrl = oldActionUrl.replace(oldSource, encodeURIComponent(newSource));
WebForm_DoPostBackWithOptions(new WebForm_PostBackOptions('custom_addLine', "", true, "", newActionUrl, false, true));
}
Please remove event.preventDefault(); from your code, it is responsible for redirection does not work
$('#custom_addLine').click(function(event){
addLine(getQueryStringParameter('ID'));
});

Custom file input using jquery restrict the user file types and filename if the user click check box it input file disable

Currently working on file upload
where the user can upload only jpeg and pdf files n the text field it has to show the filename.
less than 5mb
If user click the checkbox it should not allow to atthach file it should be disabled
Here I was confused how to set the filetypes, restrict size & how to disabled.
Here is my jquery code till now i tried
var $preview = $(".preview");
//var $acceptdiv = $("#accept_div");
//$acceptdiv.hide();
$preview.hide();
$(".check").on("change", function(){
var filename = this.value;
var files = this.files;
var URL = window.URL||window.webkitURL;
var url = URL.createObjectURL(files[0]);
$preview.attr("href", url);
$preview.show();
//$acceptdiv.show();
document.getElementById('file_name').value = filename;
$("#file_name").prop("disabled", true);
});
/* health infor addmore ends here*/
$(document).on('click', ".accpt_chk", function() {
alert("check");
if($('.accpt_chk').prop(':checked')) {
$('.checkfile').prop('disabled', true);
} else {
$('.checkfile').prop('enabled', false);
//$(this).closest("#btn_selct").removeClass('cst_select').addClass('cst_select_dis');
//$('#btn_selct').hasClass('.cst_select ').remove().addClass('.cst_select_dis');
}
//$('.qq-upload-button').prop('disabled', !this.checked);
});
Here is the fiddle Link
Kindly please helpme
Thanks in advnace
1.To check whether a checkbox is selected or not you have use .is(':checked')
like if ($('.accpt_chk').is(':checked')) {}
2. To add an attribute you can use .attr('name','value')
Demo
part of updated Js
$(document).on('click', ".accpt_chk", function() {
if ($('.accpt_chk').is(':checked')) {
$('.checkfile').attr('disabled', 'true')
} else {
$('.checkfile').removeAttr('disabled')
$('.checkfile').prop('enabled', false);
$(this).closest("#btn_selct").removeClass('cst_select').addClass('cst_select_dis');
//$('#btn_selct').hasClass('.cst_select ').remove().addClass('.cst_select_dis');
}
//$('.qq-upload-button').prop('disabled', !this.checked);
});

jQuery drag and drop image to textarea handle event

I want to make text area that will handle image drop event on it from the desktop.
I found that I could attach event to html element, but it doesn't work properly. I don't find any error, but it doesn't work.
Here is my code:
var imageDragOver = function imageDragOver(evt)
{
console.log('imageDragOver');
evt.stopPropagation();
evt.preventDefault();
}
var imageDrop = function imageDrop(evt)
{
console.log('imageDrop');
evt.stopPropagation();
evt.preventDefault();
}
document.addEventListener($('textarea'), imageDragOver, false);
document.addEventListener($('textarea'), imageDrop, false);
There is no any message in console log. What I do wrong? I don't look for an already made solutions.
To handle drop event on your area (text area or div) you need to do this:
var dropzone = document.getElementById('ta'); // paste your dropzone id here
dropzone.ondrop = function(e){
console.log('drop'); // for debugging reasons
e.preventDefault(); // stop default behaviour
readfiles(e.dataTransfer.files); // function to handle file(s) that was added to dropzone
};
Next you need to send this files to server and show it in the browser if you want.
function readfiles(files) {
var formData = new FormData(); // we initialise a new form that will be send to php
for (var i = 0; i < files.length; i++) { // if we have more that one file
previewImg(files[i]); // function to preview images
formData.append('file'+i, files[i]);
}
formData.append('moreInfo','myValuableValue');// you can append additional string info
$.ajax({
url: './path_to_file_handler.php',
type: 'POST',
data: formData,
async: true,
success: function (data) {
console.log(data);
},
cache: false,
contentType: false,
processData: false
});
}
function previewImg(file) {
var reader = new FileReader();
reader.onload = function (event) {
var image = new Image();
image.src = event.target.result; // set image source
image.width = 550; // a fake resize
document.getElementById('body').appendChild(image); // append image to body
};
reader.readAsDataURL(file);
}
Code for testing path_to_file_handler.php
<?php
print_r($_POST);
print_r($_FILES);
?>
Hope it will help somebody.
A simple way with jQuery UI, check out:
http://jqueryui.com/draggable/
http://jqueryui.com/droppable/
EDIT:
Duplicate of: Drag and drop desktop to browser HTML5 Javascript ?
Good luck! :-)

Dropzone.js uploads only two files when autoProcessQueue set to false

I use Dropzone.js and I want it to upload the dropped not automatically but when the user clicks a button. So I set the autoProcessQueue option to false. When the button is clicked the processQueue() method is called. I would suppose that now the full queue is processed. But thats not the case. Only the number of files which is specified in the parallelUploads option will be uploaded. The standard value of parallelUploads seems to be 2. Which every click 2 files are processed and uploaded.
Do I have to set parallelUploads to an very high number, for now to solve this?
Here's my full JS code:
var myDropzone = new Dropzone("div#myId", {
url: "http://www.torrentplease.com/dropzone.php",
addRemoveLinks: true,
thumbnailWidth: "80",
thumbnailHeight: "80",
dictCancelUpload: "Cancel",
autoProcessQueue: false
});
myDropzone.on("drop", function(event) {
$('.edit_tooltip .option_bar').animate({
opacity: 1,
top: "-5"
});
});
$('.edit_tooltip .option_bar .button').click(function() {
myDropzone.processQueue();
});
Add parallelUploads: 10(This is your max no)
There's a simple way to solve this which can be found here:
https://github.com/enyo/dropzone/issues/253#issuecomment-22184190
"If you want autoProcessQueue to be true after the first upload, then just listen to the processing event, and set this.options.autoProcessQueue = true; inside."
So just add
this.on("processing", function() {
this.options.autoProcessQueue = true;
});
My solution is:
// init dropzone with auto process queue false
var adPhotosDropzone = new Dropzone("#dropzone", {
autoProcessQueue: false,
parallelUploads: 3
});
$(document).on('click', '#btnUpload', function () {
// enable auto process queue after uploading started
adPhotosDropzone.options.autoProcessQueue = true;
// queue processing
adPhotosDropzone.processQueue();
});
// disable queue auto processing on upload complete
adPhotosDropzone.on("queuecomplete", function() {
adPhotosDropzone.options.autoProcessQueue = false;
});
Very late but maybe it will help someone.
I noticed when I placed maxFilesSize above parallerUploads it didn't worked.
So sequence for options should be
.
.
.
parallelUploads: 20,
maxFilesize: 2,
maxFiles: 20,
.
.
Add overdrive two event like
processing -> Allow upload all file
queuecomplete -> Return to normal
init: function () {
this.on("queuecomplete", function () {
this.options.autoProcessQueue = false;
});
this.on("processing", function () {
this.options.autoProcessQueue = true;
});
};
i used this dropzone with option (autoProcessQueue:false) and it does only upload 2 files instead of my whole files. And i found this workaround in the oligoil's answer at the git's issue
The Idea is very simple (bcs we want to upload the files one by one, remember the option! :D ).
It upload multiple but limited to 1, after one file is uploaded it trigger the next Queue!
Hope it help someone!
here's my code using that idea ( since i have 2 forms to upload, after all the images is uploaded it will submitting the other forms )
Dropzone.options.dropzoneForm = {
paramName: "file", // The name that will be used to transfer the file
autoProcessQueue: false,
addRemoveLinks:true,
parallelUploads : 1,
maxFiles : 50,
autoProcessQueue : false,
autoQueue : true,
dictDefaultMessage: "<strong>Drop files here or click to upload. </strong>",
init: function () {
....
this.on("complete", function (file) {
if (this.getUploadingFiles().length === 0 && this.getQueuedFiles().length === 0) {
console.log("END ", this.getQueuedFiles().length);
}
else {
Dropzone.forElement("#dropzoneForm").processQueue();
}
});
}
};
If you dont want to set maxFiles (default no limit) and use parallelUploads with the value you want. Read this!
I have solved the problem behaviour by setting
autoQueue: false,
autoProcessQueue: true,
Then when I want to upload the files I just add them to the queue with:
myDrop.enqueueFile(file)
But, this method just accept one file, for multiple files I'am using:
myDrop.on("addedfiles", function(files){
//wait confirmation, or do some processing with the files, then:
files.forEach(function(file){
myDrop.enqueueFile(file)
})
}
Note that "addedfiles" event it's not in the documentation yet. I captures all files dragged into the dropzone or added by the click event.
This is good because if you are using "sending" event to add POST data, or "parallelUploads" the sample code works fine and don't mess with the next files. I am using Sweet Alert 2 to ask for some tags before uploading the images.
I think that you can allow uploadMultiple and change dropzone.js file.
First, allow uploadMultiple
Next, change this line code into dropzone.js:
return this.processFiles(queuedFiles.slice(0, parallelUploads - processingLength));
for
return this.processFiles(queuedFiles.slice(0, queuedFiles.length));
A bit late, but I wasn't happy with the other answers, so here's mine.
Changing autoProcessingQueue (even temporarily) after clicking send mean that if you add another file to the dropzone while other are still queued, it will get uploaded without you having to press send again, which I didn't want. And I didn't want to use a setTimeout or a busyloop either. So here's how to do it without either :
Modify the dropzone.js file. First, in the Dropzone function, you need to add a second file array to store the queue when send is pressed :
function Dropzone(element, options) {
...
this.files = [];
this.files2 = [];
Then, save the files to it when send is clicked by modifying processQueue
Dropzone.prototype.processQueue = function() {
this.files2 = this.getQueuedFiles();
...
Finally, edit the _finished function so that when a file is done uploading, another file get sent if there was still remaining ones in the queue when send was pressed:
Dropzone.prototype._finished = function(files, responseText, e) {
var file, _i, _len;
for (_i = 0, _len = files.length; _i < _len; _i++) {
file = files[_i];
file.status = Dropzone.SUCCESS;
this.emit("success", file, responseText, e);
this.emit("complete", file);
this.files2 = this.files2.filter(function(e) { return e.status == "queued" }); // Remove the files that are finished or already being uploaded
}
if (this.options.uploadMultiple) {
this.emit("successmultiple", files, responseText, e);
this.emit("completemultiple", files);
}
if (this.options.autoProcessQueue) {
return this.processQueue();
}
else {
if (typeof this.files2 != "undefined" && this.files2.length > 0) {
this.processFiles(this.files2.slice(0,1)); // process the next file if there's one
}
}
};
This solved it for me, without changing any dropzone.js code or voiding the parallelUploads setting.
$('#submit').click(function(e){
e.preventDefault();
function tryQueue(){
var numQueued=dz.getQueuedFiles().length;
var numFiles=numQueued+dz.getUploadingFiles().length;
if(numQueued>0){
dz.processQueue();
}
if(numFiles>0){
setTimeout(tryQueue,1000);
}
else window.location='/'; //redirect when finished
}
tryQueue();
});
This assumes that dz is the dropzone instance. It works by invoking processQueue until all have been uploaded. The logic in processQueue takes care of returning if nothing needs to be done so no harm in the polling.

Having trouble with JS object literal setup

So I've setup my first JS design pattern - but I've run into an issue.
Here is my code on fiddle:
http://jsfiddle.net/jrutter/CtMNX/
var emailSignup = {
'config': {
// Configurable Options
'container': $('#email-signup'),
'emailButton': $('#email-submit'),
'emailInput': $('#email-input'),
'brontoDirectAddURL': 'URL',
'brontoListID': '0bbc03ec000000000000000000000003287b',
},
'init': function (config) {
// stays the same
// provide for custom configuration via init()
if (config && typeof (config) == 'object') {
$.extend(emailSignup.config, config);
}
// Create and/or cache some DOM elements
emailSignup.$container = $(emailSignup.config.container);
emailSignup.$button = $(emailSignup.config.emailButton);
emailSignup.$input = $(emailSignup.config.emailInput);
emailSignup.$brontoURL = emailSignup.config.brontoDirectAddURL;
emailSignup.$brontoList = emailSignup.config.brontoListID;
// Add email track to drop image pixel into for submission
emailSignup.$container.append('<div class="email-error"></div>');
emailSignup.$container.append('<div class="email-track"></div>');
// Call getEmaile
emailSignup.getEmail(emailSignup.$button, emailSignup.$input);
// make a note that the initialization is complete
emailSignup.initialized = true;
},
'getEmail': function ($button, $input) {
// click event
emailSignup.$button.click(function () {
// get the val
var $emailVal = $(emailSignup.$input).val();
// Call validateEmail
console.log($emailVal);
emailSignup.validateEmail($emailVal);
return false;
});
},
'validateEmail': function ($emailVal) {
var $emailRegEx = /^([\w-\.]+#([\w-]+\.)+[\w-]{2,4})?$/;
//console.log($emailVal);
if ($emailVal == '') {
$(".email-error").html('<p>You forgot to enter an email address.</p>');
} else if (!$emailRegEx.test($emailVal)) {
$(".email-error").html('<p>Please enter a valid email address.</p>');
} else {
$(".email-error").hide();
emailSignup.submitEmail($emailVal);
}
},
'submitEmail': function ($emailVal) {
$(".email-track").html('<img src=' + emailSignup.$brontoURL+'&email='+$emailVal+'&list1=' + emailSignup.$brontoList + '" width="0" height="0" border="0" alt=""/>');
},
};
Its a function to add a subscriber to an email list via bronto - it works perfectly when the script is included on the page and the init function is setup on the page too. But when I include the script in a shared header and try to fire the function from the document-ready, it doesnt seem to be working.
Also, if I try to pass in a 'container' - that also is breaking the script. Not sure what Im doing wrong? But if I pass in the URL - that does work!
$(function () {
emailSignup.init({
'brontoDirectAddURL':'URL','container':'#email-signup'
});
});
Any advice would be greatly appreciated!
Change the following code...
emailSignup.$container = emailSignup.config.container;
emailSignup.$button = emailSignup.config.emailButton;
emailSignup.$input = emailSignup.config.emailInput;
emailSignup.$brontoURL = emailSignup.config.brontoDirectAddURL;
emailSignup.$brontoList = emailSignup.config.brontoListID;
into the following...
// Create and/or cache some DOM elements
emailSignup.$container = $(emailSignup.config.container);
emailSignup.$button = $(emailSignup.config.emailButton);
emailSignup.$input = $(emailSignup.config.emailInput);
emailSignup.$brontoURL = $(emailSignup.config.brontoDirectAddURL);
emailSignup.$brontoList = $(emailSignup.config.brontoListID);
// Add email track to drop image pixel into for submission
emailSignup.$container.append('<div class="email-error"></div>');
emailSignup.$container.append('<div class="email-track"></div>');
You can not call append on a string. I've update your JSFiddle.
Your default config object contains jQuery collections. However, you are simply passing the string "#email-signup" as your container instead of $("#email-signup"). That's where the error is coming from. Your initial call should thusly be:
$(function () {
emailSignup.init({
'brontoDirectAddURL':'URL','container': $('#email-signup')
});
});
Note that as your initial module includes some jQuery calls, you will need to wrap the whole emailSignup mess into a $(document).ready() as well.
You may consider reconfiguring this whole thing as a jQuery plugin.

Categories

Resources