Messi Adrinho Messi Adrinho - 1 month ago 5x
Javascript Question

add more button dont work in wordpress dashboard

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"/>

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;

$("#abcd"+ abc).append($("<img/>", {id: 'img', src: 'x.png', alt: 'delete'}).click(function() {

//To preview image
function imageIsLoaded(e) {
$('#previewimg' + abc).attr('src',;

$('#upload').click(function(e) {
var name = $(":file").val();
if (!name)
alert("First Image Must Be Selected");

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(){


$('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).