add more button dont work in wordpress dashboard - javascript

im working on custom post in wordpress, in this custom post i wanna add many photos using wp_attachment the problem im having here is that when i click addmore nothing happen, its like if wordpress is ignoring my jquery file
my code
<div class="col-sm-9">
<input type="file" name="aduploadfiles[]" id="uploadfiles2" size="35" class="form-control" />
<input type="button" id="add_more2" class="upload" value="add more photo"/>
</div>
and this is the javascript im using
var abc = 0; //Declaring and defining global increement variable
$(document).ready(function() {
//To add new input file field dynamically, on click of "Add More Files" button below function will be executed
$('#add_more2').click(function() {
$(this).before($("<div/>", {id: 'uploadfiles2'}).fadeIn('slow').append(
$("<input/>", {name: 'aduploadfiles[]', type: 'file', id: 'aduploadfiles',size:'35', class:'form-control'})
));
});
//following function will executes on change event of file input to select different file
$('body').on('change', '#file', function(){
if (this.files && this.files[0]) {
abc += 1; //increementing global variable by 1
var z = abc - 1;
var x = $(this).parent().find('#previewimg' + z).remove();
$(this).before("<div id='abcd"+ abc +"' class='abcd'><img id='previewimg" + abc + "' src=''/></div>");
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(this.files[0]);
$(this).hide();
$("#abcd"+ abc).append($("<img/>", {id: 'img', src: 'x.png', alt: 'delete'}).click(function() {
$(this).parent().parent().remove();
}));
}
});
//To preview image
function imageIsLoaded(e) {
$('#previewimg' + abc).attr('src', e.target.result);
};
$('#upload').click(function(e) {
var name = $(":file").val();
if (!name)
{
alert("First Image Must Be Selected");
e.preventDefault();
}
});
});
this works fine when i try it in a wordpress pages but in dashboard itdoesn't want to work even my javascript is loaded

There are several issues:
1. $ is not available. Use jQuery
In WordPress, jQuery runs in compatibility mode, i.e. the $ shortcut is not available. You can solve this by capturing jQuery as function argument in the ready method, like this:
jQuery(document).ready(function($) {
The rest of the code in the ready callback can then continue to use $.
2. Wrong selector for file upload input element
You mentioned the wrong id in the jQuery selector: your file upload element has id uploadfiles2, not file. So change:
$('body').on('change', '#file', function(){
To:
$('body').on('change', '[name="aduploadfiles[]"]', function(){
3. Duplicate id values
Each time when you add a new button, you create a div with an id of uploadfiles2: but that id already exists. In HTML id values must be unique, otherwise unexpected things happen.
All the elements you create dynamically should get a dynamically created (distinct) id value (or no id at all).

Related

How do I access input name in php code through Javascript?

I have a PHP form with some rows. These rows have fields which look like this:
<input type="text" name="addresses[n][0]" value="mail " id="address" class="validate">
I have the following code in Javascript to add and and delete rows:
$(document).ready(function () {
$('select').material_select();
});
$(function ()
{
$(document).on('click', '.btn-add', function (e)
{
e.preventDefault();
var controlForm = $('.controls form:first'),
currentEntry = $(this).parents('.entry:first'),
newEntry = $(currentEntry.clone()).appendTo(controlForm);
newEntry.find('input').val('');
}).on('click', '.btn-remove', function (e)
{
$(this).parents('.entry:first').remove();
e.preventDefault();
return false;
});
});
My problem is, that after sending this form in POST with added rows, the added ones have the same 'n' index, because they are cloned. How can I access the 'name' attribute of them in the newEntry variable, which is a div of the whole row?
I have tried things like
newEntry.find('name').val('addressesNewName')
newEntry.find('input').getAttribute('name') = 'addressesNewName'
newEntry.find('name').setAttribute("name","addressesNewName");
newEntry.find('input').find('name').val('addressesNewName');
newEntry.find('input').attr('name') = 'newaddresses';
newEntry.find('input').attr('name').val('newaddresses');
But nothing changes the name in the field.
I don't need help with what n values to assign and so on, only how to change the name of the input field.
Have you tried?
newEntry.attr('name', 'addressesNewName');
Since you're using jQuery, accessing node attributes is easily done via:
$(node).attr('attributeName'); // get attribute value
$(node).attr('attributeName', 'newValue'); // set attribute value
jQuery API

select and remove multiple images with preview before upload

I'm looking for a plugin which allows adding multiple images, previewing, removing and submitting with some extra fields without ajax.
i have found some very good plugins like fineUploader and dropzone but they submit with ajax. with these plugins i haven't figured out how to submit without ajax.
I'm looking for a plugin which allows adding multiple images, previewing, removing and submitting with some extra fields without
ajax.
multiple images ----> <input type='file' id="myfiles" multiple="multiple" name="files[]">
previewing ---> Jquery
removing-----> Highly impossible to remove one by one image from file list,as the api is read only,however we can clear the entire file list, when the remove button is clicked.
without ajax ----> Just action the form to the controller/handler.
I don't think there's a way to achieve what you need beside using one of the plugins you have mentioned above.
You have 2 Options that I can think of currently.
use the multiple attribute on the file input type, then u can be able to use jquery to preview the images that are loaded but however we can not remove the image one by one from the filelist we can only remove the image from the preview but the server side still gonna process the image, or we can just clear the entire filelist, as I have mentioned above.
OR
we can add the file field dynamically using jquery, in this way we can be able to add one image add a time, then have an add more images button that will append a new file input to our form, with this we will be able to remove images one by one before processing in the server side.
Option 1
$('document').ready(function() {
var images = function(input, imgPreview) {
if (input.files) {
var filesAmount = input.files.length;
for (i = 0; i < filesAmount; i++) {
var reader = new FileReader();
reader.onload = function(event) {
$($.parseHTML("<img class='pic'>")).attr('src', event.target.result).appendTo(imgPreview);
}
reader.readAsDataURL(input.files[i]);
}
}
};
$('#myimg').on('change', function() {
images(this, '#previews');
});
//clear the file list when image is clicked
$('body').on('click','img',function(){
$('#myimg').val("");
$('#previews').html("");
});
});
img{
cursor: pointer;
}
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<form id="form1" enctype="multipart/form-data" action="server.php" method="post">
<input type='file' id="myimg" multiple="multiple">
<div id="previews"></div>
<p> </p>
<button type="submit">Submit</button>
</form>
Option 2
var abc = 0;
$('#add_more').click(function ()
{
$(this).before($("<div/>",{id: 'filediv'}).fadeIn('slow').append($("<input/>",
{
name: 'file[]',
type: 'file',
id: 'file'
}),
$("<br/><br/>")
));
});
$('body').on('change', '#file', function ()
{
if (this.files && this.files[0])
{
abc += 1; //increementing global variable by 1
var z = abc - 1;
var x = $(this)
.parent()
.find('#previewimg' + z).remove();
$(this).before("<div id='abcd" + abc + "' class='abcd'><img id='previewimg" + abc + "' src=''/></div>");
var reader = new FileReader();
reader.onload = imageIsLoaded;
reader.readAsDataURL(this.files[0]);
$(this)
.hide();
$("#abcd" + abc).append($("<img/>",{
id: 'img',
src: 'x.png', //the remove icon
alt: 'delete'
}) .click(function ()
{
$(this)
.parent()
.parent()
.remove();
}));
}
});
//image preview
function imageIsLoaded(e)
{
$('#previewimg' + abc)
.attr('src', e.target.result);
};
<script
src="https://code.jquery.com/jquery-3.2.1.min.js"
integrity="sha256-hwg4gsxgFZhOsEEamdOYGBf13FyQuiTwlAQgxVSNgt4="
crossorigin="anonymous"></script>
<form method="POST" action="server.php" enctype="multipart/form-data">
<div class="col-md-3 col-sm-3 col-xs-3">
<div id="filediv"><input name="file[]" type="file" id="file"/></div>
<input type="button" id="add_more" class="btn btn-primary" value="Add More Files"/><br><br>
<button type="submit" class="btn btn-success">Submit</button>
</form>
I believe this more esp option 2 can do the trick, select image, add more preview delete, then when u are happy hit the submit button then do your processing on the server. You might add styling to the preview images
Goodluck.
You can use DropzoneJS
They have a list of configurable options that you can find here. Dropzone JS Usage.
If you still need more customization then you will have to add your own code to it. Hope this helps you from writing thousand lines of code.
Without AJAX requests:
This may help you. Click here!

List selected files from file input

I want to list selected file from file input.
<div class="fileUpload myButton">
<span>Upload</span>
<input type="file" name="imageURL[]" id="imageURL" multiple="" class="file" />
</div>
<div id="file-list">
</div>
I have this code
(function () {
var filesUpload = document.getElementById("imageURL"),z
fileList = document.getElementById("file-list");
function uploadFile (file) {
var li = document.createElement("li"),
div = document.createElement("div"),
reader,
xhr,
fileInfo;
li.appendChild(div);
// Present file info and append it to the list of files
fileInfo = "<div class=\"neutral\">File: <strong>" + file.name + "</strong> with the size <strong>" + parseInt(file.size / 1024, 10) + "</strong> kb is in queue.</div>";
div.innerHTML = fileInfo;
fileList.appendChild(div);
}
function traverseFiles (files) {
if (typeof files !== "undefined") {
for (var i=0, l=files.length; i<l; i++) {
uploadFile(files[i]);
}
}
else {
fileList.innerHTML = "<div class=\"neutral\">Your browser does not support Multiple File Upload, but you can still upload your file. We recommend you to upload to a more modern browser, like Google Chrome for example.<div>";
}
}
filesUpload.addEventListener("change", function () {
traverseFiles(this.files);
}, false);
})();
But the problem is when the user selects another files it is added to the list but the old files is not uploaded when the form is submitted.
Simplified: when the user selects file1.pdf and file2.pdf
The list shows file1.pdf and file2.pdf
When he selects again another files file3.pdf and file4.pdf
the list shows file1.pdf , file2.pdf, file3.pdf and file4.pdf
But when he submit the form only file3.pdf and file4.pdf is uploaded
My question is how to remove the files which will not be uploaded from the list.
OR a way to upload all the files in the list.
Thanks in advance.
What is happening is that the input is emptied when selecting more files, hence not uploading the previously displayed files.
SOLUTION 1: To combat this you could create a new input in the change event handler, although this could get quite messy.
You would have to get all files from all the inputs on upload. You have not shown your actual upload code, so I cannot give an example in context:
filesUpload.on("change", function () {
traverseFiles(this.files); //Add initial files to list
create_new_input();
}
function create_new_input() {
var new_input = $('<input type="file" />'); //create file selector
new_input.on("change", function() {traverseFiles($(this).get(0).files);}); //
$('body').append(new_input); //Add this input to your page
}, false);
You will have to add all files that you receive in the traverseFilesto the xhr. This example uses jQuery, and I would recommend that you use it all the time!
SOLUTION 2:
Other wise you can empty the file list box on input changed:
filesUpload.addEventListener("change", function () {
document.getElementById('file-list').innerHTML = "";
traverseFiles(this.files);
}, false);
Good luck!
Your Problem is that you manipulate the value of input multiple times. The second time someone selects a file using the html file input, the originally selected files are "overwritten" from the inputs value attribute.
You could hook into your forms submit and add the files you already stored in your html.
Another way to do it would be to work with several file input elements.
So every time someone selects files and you add them to your html, hide the old file input and add a new one like this ...
adjust your html code like this:
<div class="fileUpload myButton">
<span>Upload</span>
<input type="file" class="imageUrlInput" name="imageURL[0]" id="imageURL" multiple="" class="file" />
</div>
<div id="file-list">
</div>
Adjust your Javascript like this:
function uploadFile (file) {
var li = document.createElement("li"),
div = document.createElement("div"),
reader,
xhr,
fileInfo;
li.appendChild(div);
// now here we receive the HTML input element for the files.
var currentInput = $('#imageURL');
var imageUrlInputsCount = $('.imageUrlInput').length;
// now we change the 'id' attribute of said element because id's should be unique right?
currentInput.attr('id','imageUrl_'+imageUrlInputsCount);
// now, we append a new input element with an incremented array key defined by the length of already existing input elements
currentInput.append('<input type="file" name="imageURL['+imageUrlInputsCount+']" id="imageURL" multiple="" class="file" />');
// and finally we hide the old element
currentInput.hide();
// Present file info and append it to the list of files
fileInfo = "<div class=\"neutral\">File: <strong>" + file.name + "</strong> with the size <strong>" + parseInt(file.size / 1024, 10) + "</strong> kb is in queue.</div>";
div.innerHTML = fileInfo;
fileList.appendChild(div);
}
Now make sure that in your retrieving server code (php/jsp/asp,node.js or whatever you are using) you change checking for imageURL, you iterate over imageURL since now you have several sets of imageURLs. i.e. your imageURL parameter could look like this:
imageURL = array (
0 => array(
'foo1.pdf',
'foo2.pdf',
'foo3.pdf',
),
1 => array(
'foo4.pdf',
'foo5.pdf',
'foo6.pdf',
)
3 => array(
'foo7.pdf',
'foo8.pdf',
'foo9.pdf',
)
)

How to append file name in the row it belongs to?

I have an application you can access [here][1]. When you open up the application, you will see an "Add" button on top, click this twice and you will see 2 table rows appear with each row containing it's own file input.
The problem is: suppose you try to upload a file (a small file for quick upload) in the second row's file input. After you have uploaded a file, the name of the file which has been uploaded is appended into both the top row and the second row. This is incorrect, it should only append the file name in the second row only because you used the second row's file input to upload that file.
How can I append the file name within the same row as the file input used to upload the file?
Below is the code for the form which contains the file input:
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='imageupload.php' method='post' enctype='multipart/form-data' target='upload_target' onsubmit='return imageClickHandler(this);' class='imageuploadform' >" +
"Image File: <input name='fileImage' type='file' class='fileImage' /></label><br/><label class='imagelbl'>" +
"<input type='submit' name='submitImageBtn' class='sbtnimage' value='Upload' /></label>" +
"<label><input type='button' name='imageClear' class='imageClear' value='Clear File'/></label>" +
"</p><ul class='listImage' align='left'></ul>" +
"<iframe class='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);
};
Below is the handler the form directs to when clicked:
function imageClickHandler(imageuploadform){
if(imageValidation(imageuploadform)){
return startImageUpload(imageuploadform);
}
return false;
}
Below is where the file uploading starts and stops:
function startImageUpload(imageuploadform){
$(imageuploadform).find('.imagef1_upload_process').css('visibility','visible');
return true;
}
function htmlEncode(value) { return $('<div/>').text(value).html(); }
function stopImageUpload(success, imagefilename){
var result = '';
if (success == 1){
result = '<span class="msg">The file was uploaded successfully!</span><br/><br/>';
$('.listImage').append('<div>' + htmlEncode(imagefilename) + '<button type="button" class="deletefileimage">Delete</button><br/><hr/></div>');
}
else {
result = '<span class="emsg">There was an error during file upload!</span><br/><br/>';
}
$(".deletefileimage").on("click", function(event) {
$(this).parent().remove();
});
return true;
}
CORRECT SOLUTION:
function imageClickHandler(imageuploadform){
if(imageValidation(imageuploadform)){
window.lastUploadImageIndex = $('.imageuploadform').index(imageuploadform);
return startImageUpload(imageuploadform);
}
return false;
}
$('.listImage').eq(window.lastUploadImageIndex).append('<div>' + htmlEncode(imagefilename) + '<button type="button" class="deletefileimage">Delete</button><br/><hr/></div>');
Your basic problem is:
$('.listImage')
That is a selector for "any element with the class 'listImage'". Since you've clicked add twice, there are two elements with this class, and your selector matches (and appends) to both of them.
Use a more specific selector for your append and you should be all set.
Unfortunately, I can't recommend a specific way of doing that, because I don't know how your stopImageUpload function is being called. If it's being triggered by a jQuery event handler, then you can refer to "this" inside your function to get the element that triggered the event, and you should be able to use that to figure out which .listImage to append to.
If it's not triggered by an event handler, then I would imagine that whatever function is calling it knows which file input triggered things.
Once you know which element you actually want to append to, you can target it using jQuery's eq method/selector. Here are a couple examples:
$('.listImage:eq(0)') // selects the first listImage only
$('.listImage').eq(2) // selects the third listImage only

Best way to pass JS/ css info to a form

I am sure this is so easy and I'm just a huge huge noob. I have a form on a PHP page, and it has a few normal form elements (1 textarea, 1 text field).
I am also dynamically adding 100 small images to the page, which are random, and I am using JQuery to let someone select or deselect these images:
Here is the html that loops 100 times to display the images:
<div class='avatar'><img class='avatar_image' src='$this_profile_image' name='$thisfriend'></div>
and here is the Jquery:
<script type="text/javascript">
$(document).ready(function() {
$(".avatar_image").click(function() {
$(this).toggleClass("red");
});
});
</script>
What I want to do is, when the form is submitted, have the script that processes it be able to tell which of those 100 images is selected (so it's class will be "red" instead of "avatar_image"). I am blanking on this.
You'll need to add hidden inputs with some kind of identifiers for those images, and toggle the state of those inputs based on the image selected-ness. Something like this:
Change your image markup:
<div class='avatar'>
<img class='avatar_image' src='$this_profile_image' name='$thisfriend'>
<input type="hidden" name="avatar_image[]" value="$this_profile_image" disabled="disabled" />
</div>
Change jQuery binding (and use event delegation, maybe pick a better container than document.body):
<script type="text/javascript">
$(function() {
var selClass = 'red';
$(document.body).on('click', ".avatar_image", function() {
var $this = $(this);
var $inp = $this.siblings('input[type="hidden"]');
var isSelected = $this.hasClass(selClass), willBeSelected = !isSelected;
$this.toggleClass(selClass);
if(willBeSelected) {
$inp.removeAttr('disabled');
} else {
$inp.attr('disabled', 'disabled');
}
});
});
</script>
Read the submitted data in PHP (assuming you're submitting via a POST form):
$selectedImages = $_POST['avatar_image'];
Add a ID to each image, when its clicked grab the id and then inject it into a hidden textfield
<input type="hidden" name="avatar" id="avatar" value="" />
$(".avatar_image").click(function() {
$(this).toggleClass("red");
//assign its id to the hidden field value
$("input[name='avatar']").attr('value', $(this).attr('id'));
// pass that to your DB
});
I presume your using ajax to grab this data back
success : function(callback){
$("image[id*='"+callback.avatar+"']").addClass('red');
}
Try this
PHP: Add the id for the friend to the html you had
<div class='avatar'>
<img class='avatar_image' src='$this_profile_image' name='$thisfriend' data-id='$thisFriendsId>
</div>
JS: Create an empty array. Use each function to go through push the selected id into your array. Then use post to submit to your php.
selected = [];
$(function(){
$(".avatar_image").click(function() {
$(this).toggleClass("red");
});
$('.submit').click(function(){
$('.red').each(function(){
var selectedId = $(this).data('id');
selected.push(selectedId);
});
$.post ('http://mysite.com/process.php', selected, function() { alert('succes!'); });
});
​});​

Categories

Resources