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>
Related
I'm trying to dynamically add file field to form in symfony 2 using js and PRE_SUBMIT event listener. That's what I've got:
JS:
function addFileField() {
var container = document.getElementById("files");
var new_file_field = document.createElement("input");
new_file_field.type = "file";
new_file_field.onclick = function() { addFileField(); };
new_file_field.id = "order_file" + getFileFieldsCount().toString();
new_file_field.name = "order[file" + getFileFieldsCount().toString() + "]";
container.appendChild(new_file_field);
}
Where getFileFieldsCount() simply returns how many file fields there's been created so far.
And in my listener for PRE_SUBMIT I simply have:
for ($i = 0; $i < $data['files_count']; $i++ ) {
$form->add("file$i", 'file');
}
Where files_count is a hidden field which value contains what getFileFieldsCount() returns when clicking submit button. The only problem is that form data contains only filename of the file that is supposed to be uploaded, not the file itself. I am trying to make it work for couple hours now, can someone help?
I have an input box and a go button. When the user clicks the go button I want to compare the inserted value with another value. I am trying to acquire the input value inside a function like so
function getInput(){
var entry ='';
$('button.go').on('click',function(){
var entry = $(this).siblings('.input').val();
//return entry
})
return entry
}
Basically I want to return the var entry that has an input value, so I could compare the values later in the code
var input = getInput() // this should have input value
is input > othervalue
I call getInput inside document.ready()
You are doing everything right . There are some scope related issues that is not helping you to get the expected result . My suggestion would be to define othervalue variable as global and check it inside the function like this
function getInput(){
$('button.go').on('click',function(){
var entry = $(this).siblings('.input').val();
if(entry>othervalue) //your code
});
}
I am not sure why you are binding dynamic click event inside a function . If there is nothing else you need to do here except this part, then wrap this piece of code inside document.ready.
I would suggest to declare your var entry =''; globally and assign it before comparing.
var entry="";
$('button.go').on('click',function(){
entry = $(this).siblings('.input').val();
});
//do the comparing..
You should do the comparing, after delegating the click function, inside the function.
var entry = "";
$('button.go').on('click', function(){
var entry = $(this).prev('.input').val();
if (entry < x)
// Do something
});
It remains unclear to me what you want to accomplish.
I made some code that might be somewhere near what you want.
jQuery().ready(function()
{
var startValue = $('input[name="the_input"]').val();
$('form').submit(function()
{
var currentValue = $('input[name="the_input"]').val();
$('body').append('<br />' + startValue + ' - ' + currentValue + ' = ' + (startValue - currentValue));
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<form action="#" method="post">
<input type="text" value="10" name="the_input" /><br />
<input type="submit" value="go!" />
</form>
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.
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);
});
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.