Dynamically add dropzone.js div element to the form - javascript

I have to use multiple dropzone areas to upload images. I have used the jQuery append() function to dynamically create the div.
The problem is that the dynamically created dropzone is not initialized and therefore not working.

Just make sure to call the plugin on that newly appended element. The problem is the plugin gets attached to only elements which were present initially.
So, call the plugin once again after you append the element so, it gets attached and works again.

Here is the script i have used to do the same.
I have changed the dynamically created input type text's name field by using the querySelector. The querySelector returns the reference of the elements which have custom attribute i have used data-tagline.
Dropzone.options.myDropzone = {
init: function() {
this.on("addedfile", function(file) {
_ref = file.previewTemplate.querySelector('[data-tagline]');
_ref.name = "This is my New name attribute of element";
})
},
previewTemplate:"<div class=\"dz-preview dz-file-preview\">\n "+
"<div class=\"dz-details\">\n "+
"<div class=\"dz-filename\"><span data-dz-name></span></div>\n "+
"<div class=\"dz-size\" data-dz-size></div>\n "+
"<img data-dz-thumbnail class=\"img-responsive img-thumbnail\" />\n "+
"<input type=\"text\" data-tagline />"+
"</div>\n "+
"<div class=\"dz-progress\">"+
"<span class=\"dz-upload\" data-dz-uploadprogress></span>"+
"</div>\n "+
"<div class=\"dz-success-mark\"><span>✔</span>"+
"</div>\n "+
"<div class=\"dz-error-mark\"><span>✘</span>"+
"</div>\n "+
"<div class=\"dz-error-message\"><span data-dz-errormessage></span>"+
"</div>\n"+
"</div>",
};
<div id="my-dropzone" class="dropzone" action="upload.php"></div>

In your script you need a function to create the form for dropzone, and then execute the function Dropzone.discover()
function add_dropzone() {
const drop_zone = document.createElement("form");
drop_zone.setAttribute("class","dropzone");
drop_zone.setAttribute("action","url_to_upload_files/");
drop_zone.setAttribute("id","my_dropzone");
//find a div where you want to add your dropzone
document.getElementById("div_for_dropzone").appendChild(drop_zone);
// this function will find the class="dropzone" tag and load it.
Dropzone.discover();
}
then in your html you just need to add a div with the id="div_for_dropzone"

dynamically create dz element:
var d='<div id="dzFormDiv">';
d+=' <form ';
d+=' class="dropzone"';
d+=' id="my-awesome-dropzone">';
d+=' <input type="hidden" id="dztoken" name="dztoken"> ';
d+=' <input type="hidden" id="dzt2" name="dzt2"> ';
d+=' </form> ';
d+=' <div id="dsbw">';
d+=' <button id="btnRemoveAlldz">clear</button>';
d+=' </div> ';
d+='</div> ';
append to div somewhere
$("#uploads").prepend(d);
start instance
myAwesomeDropzone = new Dropzone("#my-awesome-dropzone", { url: "../cgi/newUploader.exe"});
add options
Dropzone.options.myAwesomeDropzone = {
init: function () {
var myDropZone = this;
$("#btnRemoveAlldz").click(function () {
myDropZone.removeAllFiles();
}
);
myDropZone.on("complete", function (file) {
if(this.getUploadingFiles().length === 0 && this.getQueuedFiles().length === 0) {
consol.log("completed upload");
}
});
myDropZone.on("sending", function (file) {
// do something before uploading
});
},
error: function(){
// call error handling function
},
success: function(file,r){
// called after EACH successfull upload
file.previewElement.classList.add("dz-success");
if(r.indexOf("ok")>-1){
console.log("success");
}else{
console.log(r);
}
}
};

A bit late to the party but they thought about it. As stated in the usage part of the documentation:
Alternatively you can create dropzones programmaticaly (even on non form elements) by instantiating the Dropzone class
// Dropzone class:
var myDropzone = new Dropzone("div#myId", { url: "/file/post"});
You may have to create an element and set some properties manually.
var form = document.createElement('form');
form.classList.add('dropzone');
form.method = 'post';
form.action = '/file/post';
document.getElementById('parent').appendChild(form);
new Dropzone(form);
Don’t forget to specify an url option if you’re not using a form element, since Dropzone doesn’t know where to post to without an action attribute.

Related

append() in jquery does'nt append file second time

I have defined an input of type file and a hidden form below it,
<input type="file" name="attachment0" id="attachment0" custom-on-change="uploadfile" ng-show="attachFile" multiple/>
<form class="hidden" id="myForm" method="post" enctype="multipart/form-data" action="SupportRequest">
</form>
"custom-on-change" is an angular directive that calls the function uploadfile() after choosing files. My javascript looks as shown below
var form = $('#myForm');
var n=0;
$scope.attachFile = true;
$scope.uploadfile = function() {
if(n == 0){
var filein = $('#attachment0');
form.append(filein);
$('#attachment0').test();
}
else
{
if(n==1){
var temp = "attachment0" + '_' + n;
var file_in = $('#'+temp);
form.append(file_in);
$('#'+temp).test();}
}
};
$.fn.test = function() {
return this.each(function(){
n++;
$(this).attr('id', this.id + '_' + n);
$(this).attr('name', this.name + '_' + n);
});
};
Am trying to append files twice to the form myForm. When i choose files second time, even after appending, i see that the previously appended input with id="attachment0" is not present in myForm and the input of id="attachment0_1" is present in the form.
Here am trying to upload multiple files multiple times, that is why am dynamically changing the id of the input in test().
I want both input with id attachment0 and attachment0_1 in myForm.
Does anyone know how this can be fixed? And explain this behavior too.
Change your code from form.append(filein) to form.append($('#attachment0').clone()).
It work then. You should use .clone() method to copy elements .
.append() just moves the element from one place to another but for copying first create the copy of the element using .clone() and then append it to your form
looks like in test function you are replacing id,
$(this).attr('id', this.id + '_' + n);
Would is not be better to use ng-repeat? Something like this:
Controller:
$scope.files = [...] // list of files
$scope.uploadfile = function() {
// So stuff to get the file
$scope.files.push(filein);
};
Html:
<!-- Inside the form -->
<div ng-repeat="file in files">{{file}}</div>

Dynamically building a button with an onClick

I am dynamically building a button in JavaScript, this will include an onClick event. The onClick event needs to focus a field which is stored in a variable.
I couldn't find a way of using the field variable itself, so instead decided to try using the field.selector property from the JQuery object, this WILL contain " ".
Here is a code snippet of the construction as it stands.
InvalidField.prototype.getMessageStructure = function(){
var structure = '<div class="invalidMessage"><span>' + this._message + '</span>
<button class="inputButton"
Value="Go To Field"
onclick=\'goToFieldFromAlert($(\'' + this._field.selector + '\'))\'
/>
</div>';
return structure;
};
This is outputting:
<button class="inputButton"
value="Go To Field"
onclick="goToFieldFromAlert($(" input[name="applicant.email" ]'))'="">
</button>
As you can see, the quotations will not be out put correctly and so break on click.
Can anyone foresee a better way of performing this function, or correcting the quotations? I see from this SO Answer that the DOM doesn't respect the quotations which is what is currently causing me the issue.
Kind Regards.
As I mentioned in comment, avoid using onclick at all. jQuery event handlers are far more flexible (and support multiple event handlers).
1) Inject the fieldname (only, not the jQuery selector) into a data- attribute:
InvalidField.prototype.getMessageStructure = function(){
var structure = '<div class="invalidMessage"><span>' + this._message + '</span>
<button class="inputButton"
value="Go To Field" data-field="' + this._field.name + '"/>
</div>';
return structure;
};
2) Use a delegated event handler to get all clicks on inputButtons with less overhead. Extract the field name and do the jQuery where it belongs:
$(document).on('click', '.inputButton', function() {
var $button = $(this);
var field = $button.data('field');
goToFieldFromAlert('input[name="' + field + '"]');
});
You should create element using jQuery. This is much cleaner and error free approach
An example with your code
InvalidField.prototype.getMessageStructure = function(){
var structure =
$('<div></div>').append(
$('<span></span>').text(this._message)
);
structure.append(
$('<button></button>')
.addClass('inputButton')
.text("Go To Field")
.click(function(){
goToFieldFromAlert($(this._field.selector));
})
);
return structure;
};
The following example will dynamically add buttons:
hello.forEach( function(result) {
var card = document.createElement("input");
card.type = "button";
card.onclick = function() {
newcard( result );
}
card.value = value; // some value
card.style.backgroundColor="#5ABC7B";
document.body.appendChild(card);
});

How I find the checkbox by id and apply attribute on string using JQuery?

I have a following html string of contentString:
var content =
'<div id="content">' +
'<div>' +
'<input name="tBox" id="select" type="checkbox" value="" '+
'onclick="changeView()"> Select for operation' +
'<p style="text-align:right">View details</p>' +
'</div>' +
'</div>';
Here, How I find the checkbox select by id and add attribute checked on changeView() function?
function changeView(m) {
//find the select id from content string
var checkbox = content.find($('#select'+m));
// Apply the checked property on checkbox.
checkbox.attr("checked","checked");
}
Thanks in advance.
If you convert it to a JQuery object first then you can do it like this:
var contentObj = $(content);
var checkbox = contentObj.find("#select");
checkbox.attr("checked", true);
then if you need it back at html string:
content = contentObj[0].outerHTML;
Note: If outerHTML is not working as expected, the following JQuery can be used as an alternative:
content = contentObj.clone().wrap('<div>').parent().html();
If m is meant to be the id you want to find (e.g. "select"), then use this:
var checkbox = contentObj.find("#" + m);
Live Example: Here is a working example
Here is the complete function for easy reference:
function changeView(m) {
var contentObj = $(content);
var checkbox = contentObj.find("#" + m);
checkbox.attr("checked", true);
content = contentObj[0].outerHTML;
}
You need to compile the string into a DOM object first by wrapping it in a jQuery call first. Then you can use the find method.
So:
var dom = $(content),
select = dom.find('#select');
In any case, there is no need to add the 'checked' attribute, because when you click the checkbox, it will automatically become checked.
If however, you want to still programmatically check it:
select.on('click', function () {
this.attr('checked', 'checked');
});
Simply like this
function changeView(m) {
//find the select id from content string
var checkbox = content.find('#select');
// Apply the checked property on checkbox.
checkbox.attr("checked","checked");
}
if you want to pass id then
function changeView(m) {
//find the select id from content string
var checkbox = content.find("#" + m);
// Apply the checked property on checkbox.
checkbox.attr("checked","checked");
}
Since you're using the onclick handler, you don't really need to do any of that :
in html : onclick="changeView(this);"
function changeView(box) {
if(box.checked) { stuff; }
// or get jquery ref to that box :
$(box).prop("checked", true);
}

Embedding javascript object in dynamically created html

I have a js function that recieves an array of items. The function itself creates html content dynamicly using a call to jquery html function. The problem is that I don't remember how to embed correctly the array inside the appended html. For example,
var ErrorsNotifier = {
init: function(items) {
var template = '<div id="message">';
template += '<div id="id">some message.<br /><br />';
template += '<div class="errorsList">error desc</div></div>';
template += '';
template += '';
template += '<input type="image" src="someimage" alt="" class="" onclick="window.open("someurl");"/></div>';
$("#content").html(template);
}
}
After the html will be rendered to the body, clicking on the anchor tag return the following error - Uncaught SyntaxError: Unexpected identifier
inspecting the anchor tag in the browser will show the following
a href="#" class="goback" onclick="ErrorsNotifier.Back([object Object]);"
Try
var ErrorsNotifier = {
init: function(items) {
...
var $template = $(template);
$template.find('a.goback').on('click', function(){ErrorsNotifier.Back(items);});
$("#content").empty().append($template);
}
}
notice I used .on() to attach the event handler.
var ErrorsNotifier = {
init: function(items) {
var template = 'Link';
$("#content").html(template);
},
Back: function(x){ alert(x); }
};
Check this

It is only uploading first row's file input

I have a application which you can access here. If you open the application please click on the "Add" button a couple of times. This will add a new row into a table below. In each table row there is an AJAX file uploader.
Now the problem is that if I click on the "Upload" button in any row except the first row, then the uploading only happens in the first row so it is only uploading the first file input only.
Why is it doing this and how can I get it so that when then the user clicks the "Upload" button, the file input within that row of the "Upload" button is uploaded and not the first row being uploaded?
Below is the full code where it appends the file AJAX file uploaded in each table row:
function insertQuestion(form) {
var $tbody = $('#qandatbl > tbody');
var $tr = $("<tr class='optionAndAnswer' align='center'></tr>");
var $image = $("<td class='image'></td>");
var $fileImage = $("<form action='upload.php' method='post' enctype='multipart/form-data' target='upload_target' onsubmit='startUpload();' >" +
"<p id='f1_upload_process' align='center'>Loading...<br/><img src='Images/loader.gif' /><br/></p><p id='f1_upload_form' align='center'><br/><label>" +
"File: <input name='fileImage' type='file' class='fileImage' /></label><br/><label><input type='submit' name='submitBtn' class='sbtn' value='Upload' /></label>" +
"</p> <iframe id='upload_target' name='upload_target' src='#' style='width:0;height:0;border:0px solid #fff;'></iframe></form>");
$image.append($fileImage);
$tr.append($image);
$tbody.append($tr);
}
function startUpload(){
document.getElementById('f1_upload_process').style.visibility = 'visible';
document.getElementById('f1_upload_form').style.visibility = 'hidden';
return true;
}
function stopUpload(success){
var result = '';
if (success == 1){
result = '<span class="msg">The file was uploaded successfully!<\/span><br/><br/>';
}
else {
result = '<span class="emsg">There was an error during file upload!<\/span><br/><br/>';
}
document.getElementById('f1_upload_process').style.visibility = 'hidden';
document.getElementById('f1_upload_form').innerHTML = result + '<label>File: <input name="fileImage" type="file"/><\/label><label><input type="submit" name="submitBtn" class="sbtn" value="Upload" /><\/label>';
document.getElementById('f1_upload_form').style.visibility = 'visible';
return true;
}
UPDATE:
Current Code:
var $fileImage = $("<form action='upload.php' method='post' enctype='multipart/form-data' target='upload_target' onsubmit='startUpload(this);' >" +
"<p class='f1_upload_process' align='center'>Loading...<br/><img src='Images/loader.gif' /><br/></p><p class='f1_upload_form' align='center'><br/><label>" +
"File: <input name='fileImage' type='file' class='fileImage' /></label><br/><label><input type='submit' name='submitBtn' class='sbtn' value='Upload' /></label>" +
"</p> <iframe class='upload_target' name='upload_target' src='#' style='wclassth:0;height:0;border:0px solclass #fff;'></iframe></form>");
function stopUpload(success, source_form){
var result = '';
if (success == 1){
result = '<span class="msg">The file was uploaded successfully!<\/span><br/><br/>';
}
else {
result = '<span class="emsg">There was an error during file upload!<\/span><br/><br/>';
}
$(source_form).find('.f1_upload_process').style.visibility = 'hidden';
$(source_form).find('.f1_upload_form').innerHTML = result + '<label>File: <input name="fileImage" type="file"/><\/label><label><input type="submit" name="submitBtn" class="sbtn" value="Upload" /><\/label>';
$(source_form).find('.f1_upload_form').style.visibility = 'visible';
return true;
}
Why am I getting an error on this line below:
$(source_form).find('.f1_upload_form').style.visibility = 'visible';
Without seeing the full cose, your problem seems to be that you are working with ID's, which must be unique within one document. If several elements are using the same ID, in the best case a browser will use the first one (which it does here), in the worst case nothing will work.
When adding a new upload form, you have to give the elements in it unique ID's. You could do that simply by attaching a counting variable to window, e.g.
$(document).ready( function(){ window.formCount=0; } );
You could then add that number to the ID of the newly added form.
Apart from this, by using the this variable, you can carry a reference to the correct form through, e.g. like onsubmit='startUpload(this);' as well as function startUpload(f){...
You should then be able to access things within the form using $(f).find(...).
There are many ways to make this work and solve the issue of multiple ID's. What I would do: var $fileImage = $("<form action... In this form where it says id I would instead use class. Then as above, change the onsubmit (in the same line) by adding "this" to its brackets. Then change the function startUpload as here:
function startUpload(source_form){
$(source_form).find('.f1_upload_process').css('visibility','visible');
$(source_form).find('.f1_upload_form').css('visibility','hidden');
return true;
}
You have to do the same thing for other functions where you want to access something inside the form that is sending a file. Pass a reference to the form to the function using this in the function call's brackets, then access things inside the form as I showed above.

Categories

Resources