blueimp File Upload fires add event multiple times - javascript

I'm trying to build upload module that will be used in my website project. I've selected blueimp File Upload because of all configuration options that it gives.
Idea is to have button, that will show modal window with upload module.
My (almost) working prototype is available here: http://jsfiddle.net/Misiu/4Th3u/
What I want now is to limit number of files user can select and file size. Because I'm using non-ui version I can't use maxNumberOfFiles and maxFileSize options.
I've created add callback:
add: function (e, data) {
var uploadErrors = [];
console.log('add event');
$.each(data.originalFiles, function(index,file) {
console.log(file.name);
if (file.size && file.size > 1024 * 1024 * 5) {
uploadErrors.push('File "' + file.name + '" is too large');
}
})
if (uploadErrors.length > 0) {
alert(uploadErrors.join("\n"));
} else {
var tpl = $('<li class="working"><input type="text" value="0" data-width="36" data-height="36"' +' data-fgColor="#0788a5" data-readOnly="1" data-bgColor="#3e4043" /><p></p><span></span></li>');
tpl.find('p').text(data.files[0].name)
.append('<i>' + formatFileSize(data.files[0].size) + '</i>');
data.context = tpl.appendTo(ul);
tpl.find('input').knob();
tpl.find('span').click(function () {
if (tpl.hasClass('working')) {
jqXHR.abort();
}
tpl.fadeOut(function () {
tpl.remove();
});
});
var jqXHR = data.submit();
}
}
Problem is that add is fired multiple times, if I select 2 files I get 2 events.
Here is how console looks after selecting two files:
add event
file1.gif
file2.gif
add event
file1.gif
file2.gif
I would like to limit number of files and file size, but because of this bug it's not easy.

I can't answer your specific question but I've had to overcome the issue of validating selected files before upload. You can use the maxFileSize properties in the non-ui version, you just need to surface any errors to the UI yourself. You also need to ensure that the process and validate JS files are also referenced on the page.
Here's my solution which unfortunately has the progress stuff stripped out but the image preview left in! It shouldn't be too hard for you to hack the template stuff to suit your needs though.
My form looks like this:
<form id="FileUpload" action="/Expense/UploadReceipt" method="POST" enctype="multipart/form-data">
<!-- The fileupload-buttonbar contains buttons to add/delete files and start/cancel the upload -->
<div class="row fileupload-buttonbar">
<div class="col-md-12">
<input type="file" name="files[]" multiple class="btn btn-default">
<button type="reset" class="btn btn-danger cancel">
<i class="glyphicon glyphicon-ban-circle"></i>
<span>Cancel All</span>
</button>
<button type="submit" class="btn btn-success start">
<i class="glyphicon glyphicon-upload"></i>
<span>Start upload</span>
</button>
</div>
</div>
<!-- The loading indicator is shown during image processing -->
<div class="fileupload-loading"></div>
<br>
<!-- The table listing the files available for upload/download -->
<table class="table table-striped"><tbody class="files" data-toggle="modal-gallery" data-target="#modal-gallery"></tbody></table>
</form>
My File upload initialisation looks like this:
$('#FileUpload').fileupload({
// Uncomment the following to send cross-domain cookies:
//xhrFields: {withCredentials: true},
url: uploadUrl + data,
dataType: 'json',
headers: {
Accept: "application/json"
},
accept: 'application/json',
maxFileSize: 5000000, //5mb
sequentialUploads: true,
resizeMaxWidth: 1920,
resizeMaxHeight: 1200,
acceptFileTypes: /(.|\/)(gif|jpe?g|png|pdf)$/i,
uploadTemplateId: null,
downloadTemplateId: null,
uploadTemplate: function (o) {
var rows = $();
$.each(o.files, function (index, file) {
var row = $('<tr class="template-upload fade">' +
'<td class="preview"><span class="fade"></span></td>' +
'<td class="name"><strong class="error text-danger"></strong></td>' +
'<td class="size"></td>' +
(file.error ? '<td class="error" colspan="1"></td>' :
'<td class="actions-col">' +
'<button class="btn btn-danger cancel"><i class="glyphicon glyphicon-ban-circle"></i> <span>Cancel</span></button> ' +
'<button class="btn btn-success start"><i class="glyphicon glyphicon-upload"></i> <span>Start</span></button>' +
' </td>') + '</tr>');
row.find('.name').text(file.name);
row.find('.size').text(o.formatFileSize(file.size));
if (file.error) {
row.find('.error').text(
locale.fileupload.errors[file.error] || file.error
);
}
rows = rows.add(row);
});
return rows;
},
downloadTemplate: function (o) {
var rows = $();
$.each(o.files, function (index, file) {
var row = $('<tr class="template-download fade">' +
(file.error ? '<td></td><td class="name"></td>' +
'<td class="size"></td><td class="error" colspan="2"></td>' :
'<td class="preview"></td>' +
'<td class="name"><a></a></td>' +
'<td class="size"></td><td colspan="2"></td>'
));
row.find('.size').text(o.formatFileSize(file.size));
if (file.error) {
//row.find('.name').text(file.name);
//row.find('.error').text(
// locale.fileupload.errors[file.error] || file.error
//);
} else {
row.find('.name a').text(file.name);
var extension = file.name.substring(file.name.length - 3, file.name.length);
if (extension == "pdf") {
row.find('.name a').attr('target', '_blank');
} else {
row.find('.name a').addClass("fancyImageLink");
}
if (file.thumbnail_url) {
row.find('.preview').append('<a><img></a>')
.find('img').prop('src', file.thumbnail_url);
row.find('a').prop('rel', 'gallery');
}
row.find('a').prop('href', file.url);
row.find('.delete')
.attr('data-type', file.delete_type)
.attr('data-url', file.delete_url);
}
rows = rows.add(row);
});
return rows;
}
});
The error handling is done here:
$('#FileUpload').bind('fileuploadprocessalways', function (e, data) {
var currentFile = data.files[data.index];
if (data.files.error && currentFile.error) {
$('.files tr').eq(data.index).find(".start").prop('disabled', true);
if (currentFile.error == "File is too large") {
$('.files tr').eq(data.index).find(".size").addClass('field-validation-error');
} else {
$('.files tr').eq(data.index).find(".name").addClass('field-validation-error');
}
$("#ReceiptUploadAlert p").text(currentFile.name + ": " + currentFile.error);
$("#ReceiptUploadAlert").show();
return;
}
});
Hope this helps you in some way.

After
var jqXHR = data.submit();
add return false;, this will prevent the upload to submit until you clicked on start uplaod
reference from Using the submit callback option

Related

JSON get data using post-method

I want to get a JSON file from another server xyz.com (not writhing here original site name for safety) for my HTML page but the problem is that the website xyz.com only supports HTTP POST requests.
To check if my HTML code is working fine I use HTTP GET method and upload JSON data on another site that supports HTTP GET request. And I found that it is working fine. But when I try for HTTP POST method it is not working. Can you help me?
I am using currently and working fine
<script>
$(function() {
var people = [];
$.get('https://api.myjson.com/bins/c307c',function(data) {
$.each(data.video, function(i, f) {
HTML CODE FOR xyz.com and it also return a .json file
<html>
<head>
<form action="https://www.xyz.php" method="POST" >
<div class="container" style="width:100%;">
<center></center>
</div>
<div class="container" style="width:100%;">
<label for="userId"><b>UserId</b></label>
<input type="number" placeholder="Enter Your User Id" name="userId" autofocus required>
<label for="Passkey"><b>Passkey</b></label>
<input type="number" placeholder="Enter Passkey" name="Passkey" required>
<button type="submit" >GET Json File From Server</button>
</div>
</form>
This is i tried but not working
<script>
$(function() {
var people = [];
$.post('https://xyz.php', usedId=5&passkey=55, function(data) {
$.each(data.video, function(i, f) {
Try this way code
$.post( "https://xyz.php", { usedId: 5, passkey: 55},
function(data) {
//your code
} );
Please make necessery change so that when i click on button it take data from server and show in a table format
<html>
<head>
<form action="https://xyz.php" method="POST" >
<div class="container" style="width:100%;">
<center></center>
</div>
<div class="container" style="width:100%;">
<label for="userId"><b>UserId</b></label>
<input type="number" placeholder="Enter Your User Id" name="userId" autofocus required>
<label for="passKey"><b>Passkey</b></label>
<input type="number" placeholder="Enter Passkey" name="passKey" required>
<button type="submit" >GET DATA</button>
</div>
</form>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.2/jquery.min.js"> </script>
<script>
$(function() {
var people = [];
$.post( "xyz.php",function(data) {
$.each(data.video, function(i, f) {
var link = "https://www.youtube.com/embed/"+ f.video;
var tblRows = "<tr>" +
"<td>" + f.videoName + "</td>" + "<td>" + f.date + "</td>" + "<td>" + f.time + "</td>" +
"<td>" + f.videoDuration + "</td>" + "<td>" + f.liveStatus + "</td>" + "<td><a target='_blank' href='"+link+"'>"+link+"</a></td>" + "</tr>";
$(tblRows).appendTo("#userdata tbody");
});
});
});
</script>
</head>
<body>
<div class="wrapper">
<div class="profile">
<table id= "userdata" width="50%" border="2">
<thead>
<th>VIDEO NAME</th>
<th>DATE</th>
<th>TIME</th>
<th>DURACTION</th>
<th>LIVE STATUS</th>
<th>LINK</th>
</thead>
<tbody>
</tbody>
</table>
</div>
</div>
</div>
</html>
Some changes I suggest:
Give the form an ID, in this case login seems like an appropriate ID
Standardize your capitalization for form fields
Here's some code to get you started. You'll notice I'm creating your data twice. Decide if you want to build your data by hand or use jQuery's serialization to do it for you. Since this is a simple form, the latter is probably fine.
I'm also getting the AJAX endpoint right from the form so you aren't repeating yourself there.
// when the document has loaded...
$(document).ready(function () {
// if the user is already logging in
var login = false;
// when the form is submitted...
$('#login').on('submit', function (event) {
// block the form if it's already been submitted
if (login) {
event.stopPropagation();
event.preventDefault();
return;
}
// lock the form
login = true;
// get a handle on the form
// I use $ as a prefix to differentiate jQuery objects
// currentTarget is the subject of the event
var $form = $(event.currentTarget);
var url = $form.prop('action');
/*
* MANUAL
*/
// form fields are added to the form object as properties by name attribute
// note that they are not jQuery objects
var data = {
userId: $form.userId.value,
passKey: $form.passKey.value
};
/*
* AUTOMATIC
*/
// uses jQuery's form serialization to automatically create an object mapping names to values
var data = $form.serialize();
$.post(url, data)
// on success
.done(function (data, status, request) {
$.each(data.video, function (i, f) {
var link = "https://www.youtube.com/embed/"+ f.video;
// backslash at the end of a string means to continue the string on the next line
var $row = $('<tr>\
<td>' + f.videoName + '</td>\
<td>' + f.date + '</td>\
<td>' + f.time + '</td>\
<td>' + f.liveStatus + '</td>\
<td><a target="_blank" href="' + link + '">' + link + '</a></td>\
</tr>');
$row.appendTo('#userdata tbody');
})
// on failure
.fail(function (request, status, error) {
window.alert('Failed with a status of ' + status + ': ' + error);
})
// executes after either of the above
// parameters are inconsistent and use either done's or fail's
.always(function () {
// do cleanup, i.e. unlock form submission, close modal dialogs, etc.
login = false
});
// stop default form submission
event.stopPropagation();
event.preventDefault();
});
});

jquery function on button click from ajax request

So im building this page where i am including a file input using ajax, but i am not able to trigger jquery when a the file is changed. is this a normal thing or should this just work? I am trying to get the filename displayed in the input type text field.
My ajax call
$('.wijzigproduct').on('click', function () {
var productvalue = $(this).val();
$.ajax({
url: "includes/productwijzigen.php?q=" + productvalue,
success: function (result) {
$('#editproduct').html(result);
}
});
});
My input fields:
<div class="input-group">
<span class="input-group-btn">
<span class="btn btn-default btn-file">
Bladeren… <input type="file" name="imgInpnew" id="imgInpnew">
</span>
</span>
<input type="text" class="form-control" id='imgOutpnew' readonly>
</div>
<img id='imgshownew'/>
My jquery:
$('#imgInpnew').change(function () {
var filename = $('#imgInpnew').val();
filename = filename.substring(filename.lastIndexOf("\\") + 1, filename.length);
$('#imgOutpnew').val(filename);
});
The change() binding you're using is called a "direct" binding which will only attach the handler to elements that already exist. It won't get bound to elements created in the future.
Since you have generated DOM using jQuery, you have to create a "delegated" binding by using on() . Here is the solution base on the code you have provide on jsfiddle.net/a70svxto
$.ajax({
url: "/echo/js/?js=<div class=\"input-group\"><span class=\"input-group-btn\"><span class=\"btn btn-default btn-file\">search… <input type=\"file\" name=\"imgInpnew\" id=\"imgInpnew\"></span></span><input type=\"text\" class=\"form-control\" id='imgOutpnew' readonly></div><img id='imgshownew\'/>",
success: function(result) {
$('#div').html(result);
}
});
$('#div').on('change', '#imgInpnew', function() {
var filename = $('#imgInpnew').val();
filename = filename.substring(filename.lastIndexOf("\\") + 1, filename.length);
$('#imgOutpnew').val(filename);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div id='div'></div>
well you are attaching the change event to a not existing element in the DOM.
you have to first add the element into the DOM and then attach the event to the element
$.ajax({
url: "/echo/js/?js=<div class=\"input-group\"><span class=\"input-group-btn\"><span class=\"btn btn-default btn-file\">search… <input type=\"file\" name=\"imgInpnew\" id=\"imgInpnew\"></span></span><input type=\"text\" class=\"form-control\" id='imgOutpnew' readonly></div><img id='imgshownew\'/>",
success: function(result) {
$('#div').html(result);
$('#imgInpnew').change(function() {
var filename = $('#imgInpnew').val();
filename = filename.substring(filename.lastIndexOf("\\") + 1, filename.length);
$('#imgOutpnew').val(filename);
});
}
});
https://jsfiddle.net/a70svxto/

Handling post on dynamic row on a html table with jquery

I have a dynamic table that I will be submitted to database.
The html is looked like this :
<form id="upload">
<div class="box-body">
<div class="row">
<div class="col-xs-12 col-md-12">
<div class="box-body table-responsive no-padding">
<table class="table table-hover" id="tableReport">
<thead>
<th>TYPE</th>
<th>ITEM</th>
<th>DAMAGE</th>
<th>REPAIR</th>
<th>REMARKS</th>
<th>MANHOUR</th>
<th><button class="btn btn-block btn-primary" id="addRow" type="button">ADD</button></th>
</thead>
<tbody>
<!--GENERATED BY JQUERY-->
</tbody>
</table>
</div>
</div>
</div>
</div><!-- /.box-body -->
<div class="box-footer">
<button class="btn btn-info" type="submit">Upload</button>
</div>
</form>
See, on my <th>, I have a button with id addRow that have a function to add a row on a last row.
This is the code :
$(document).on('click', '#addRow', function () {
var selType = '<select class="form-control" name="type">';
var selItem = '<select class="form-control" name="item">';
var selDamage = '<select class="form-control" name="damage">';
var selRepair = '<select class="form-control" name="repair">';
$.each(<?php echo json_encode($type); ?>, function (i, elem) {
selType += '<option>' + elem.NAMA_TYPE + '</option>';
});
$.each(<?php echo json_encode($item); ?>, function (i, elem) {
selItem += '<option>' + elem.NAMA_ITEM + '</option>';
});
$.each(<?php echo json_encode($damage_codes); ?>, function (i, elem) {
selDamage += '<option>' + elem.NAMA_DAMAGE + '</option>';
});
$.each(<?php echo json_encode($repair_codes); ?>, function (i, elem) {
selRepair += '<option>' + elem.NAMA_REPAIR + '</option>';
});
selType += '</select>';
selItem += '</select>';
selDamage += '</select>';
selRepair += '</select>';
$("#tableReport").find('tbody').append('<tr><td>' + selType +
'</td><td>' + selItem +
'</td><td>' + selDamage +
'</td><td>' + selRepair +
'</td><td><input type="text" class="form-control name="remarks" placeholder="Describe it..">' +
'</td><td><input type="text" class="form-control time" name="manhour">' +
'</td><td><button class="btn btn-block btn-danger">Delete</button>' +
'</td></tr>');
$(".time").inputmask("hh:mm");
});
Now, this is the problem. How to handling the form. When <button class="btn btn-info" type="submit">Upload</button> is clicked to submit, I will handled it use jquery ajax. The code looked like this
$(document).on('submit', '#upload', function(){
/*First, How to handled the dynamic row ?? */
/* Commonly, I use var aVar = $('selector').val(); */
/* Ex, I have two rows, How bout to handle two select option in different row ?*/
$.ajax({
url: 'LINK TO CHECK THE POST if has SUBMITTED',
type: 'POST',
data : {/*dynamic row that will be passed : data*/}
dataType: 'json',
success: function(obj) {
})
return false;
});
How can I handle that dynamic row, and how can I debug if the post have success ?
UPDATED
This code to check the condition of a ship container. If a container have many damage, it will be representated with one row as one damage. If the container have 3 damage, it will be have 3 rows. I want to submit it on a table in my database in tbl_damage_detail. I have plan to multiple insert. So, I Imagine to store that rows into an array. with foreach, I will be inserted them.
JSFIDDLE
If the inputs are added correctly to the form you just need to submit the form with AJAX, no need for anything special, one way is to use the jQuery serialize() method like this.
$(document).on('submit', '#upload', function(event){
$.ajax({
url: 'LINK TO CHECK THE POST if has SUBMITTED',
type: 'POST',
data : $(this).serialize(),
dataType: 'json',
success: function(obj) {
})
event.preventDefault();
});
with your code,i really don't know what you want to do .
first, "on" is used to bind event with dynamic dom ,but id=addRow is not a dynamic dom,it is unnecessary to use on
"$(document).on('click', '#addRow', function () {"
just use $("#addRow").click( function () {...})
and then, <form id="upload">, i am not sure you have decide to post date to service with submit, in fact ,here is a dynamic table ,if you use submit to post your data ,it may complex with your whole table data .(using submit , input must set the name tag)
i suggest you should handle each row data
//get every row data
var tableData = [] ;
$("#tableReport tbody tr").each( function(){
var tr = &(this);
var text2 = tr.find(".time").val(); //should use more clean tag
var data = {test2:test2}//...
tableData.push(data)
//use ajax with the data
});
//next handle the tableData with ajax
this scene is very fat to mvvm like: angular , vue.js or avalon.js ,use one of them,with more clean but less code .

Javascript error on vote up/down system

I've trying to adopt script for voting up and down with ajax and jquery from one tutorial. The problem (I think) is that in the tutorial the script is used with jquery-2.1.1 but I use jquery-1.10.1
This is the HTML part
<div id="links-'.$row["image_id"].'">
<input type="hidden" id="votes-'.$row["image_id"].'" value="'.$row["votes"].'">
<input type="hidden" id="vote_rank_status-'.$row["image_id"].'" value="'.$vote_rank.'">
<div class="btn-votes">
<input type="button" title="Up" class="up" onClick="addVote('.$row['image_id'].',"1")"'.$up.' />
<div class="label-votes">'.$row["votes"].'</div>
<input type="button" title="Down" class="down" onClick="addVote('.$row['image_id'].',"-1")"'.$down.'/>
</div>
</div>
Here is the script.js which should pass clicked button to add_vote.php
function addVote(image_id,vote_rank) {
$.ajax({
url: "add_vote.php",
data:'image_id='+image_id+'&vote_rank='+vote_rank,
type: "POST",
beforeSend: function() {
$('#links-' + image_id + ' .pull-right').html("<img src='LoaderIcon.gif' />");
},
success: function(vote_rank_status){
var votes = parseInt($('#votes-' + image_id).val());
var vote_rank_status; // = parseInt($('#vote_rank_status-' + id).val());
switch(vote_rank) {
case "1":
votes = votes + 1;
// vote_rank_status = vote_rank_status + 1;
break;
case "-1":
votes = votes-1;
//vote_rank_status = vote_rank_status - 1;
break;
}
$('#votes-' + image_id).val(votes);
$('#vote_rank_status-' + image_id).val(vote_rank_status);
var up, down;
if (vote_rank_status == 1) {
up = "disabled";
down = "enabled";
}
if (vote_rank_status == -1) {
up = "enabled";
down = "disabled";
}
var vote_button_html = '<input type="button" title="Up" id="up" onClick="addVote(' + image_id + ',\'1\')" ' + up + ' /><div class="label-votes">' + votes + '</div><input type="button" title="Down" id="down" onClick="addVote(' + image_id + ',\'-1\')" ' + down + ' />';
$('#links-' + image_id + ' .pull-right').html(vote_button_html);
}
});
}
When I click vote up or down nothing happen on the page. Didn't add new vote and didn't insert into database.
This is what I see in console of firefox when I click on button
SyntaxError: expected expression, got end of script
and this but I'm not sure if is relevant to this script. Showing that the error is in file jquery-1.10.1.min.js
Empty string passed to getElementById().
Your onclick functions appear to have syntax errors.
onClick="addVote('.$row['image_id'].',"1")"
As you can see, you are using double quotes (around the number 1) inside double quotes. Try:
onClick="addVote('.$row['image_id'].',\"1\")"

Running external javascript function from a button clicked that was created dynamically using jquery in Wordpress

I am trying to execute the function that was created separately called uploads.js . This javascript file is a custom image uploader function to be used in Wordpress. I was able to run that javascript file whenever i create a new button just by the of the HTML by sending the needed parameters.
There is a part where i created a dynamic button creation function using jquery, where whenever a 'PLUS' sign button is pressed, that function will trigger and a new button is added. The id of that button is automatically incremented by one.
The problem here is, whenever i click on the button that was created not by using the dynamic button function, it was able to execute the uploads.js function. But the dynamic created buttons are not able to. It seems like the id of the dynamic button was not detected. I even inspect the element of that page, the id that was sent is exactly the same from what I have sent as a parameter to the uploads.js function.
Is there something that i have missed or I have done wrong? Below are the codes:
HTML
<tr class="form-field">
<th scope="row">
<label for="component1"> Component 1</label>
<br></br>
<input type='button' class="button button-large" value='+' id='addButton'>
<input type='button' class="button button-large" value='-' id='removeButton'>
<input type='button' class="button button-large" value='Get TextBox Value' id='getButtonValue'>
</th>
<td>
<div id='TextBoxesGroup'>
<div id="ImageDiv1">
<input id="section2_1" class="button" type="button" value="Upload Image" name="upload_s2_1"/>
</div>
<div id="TextBoxDiv1">
<label>Title #1 : </label>
<input type='text' id='title1' />
</div>
<div id="DescDiv1">
<label>Description #1 : </label>
<input type='text' id='description1' /><br></br>
</div>
</div>
</td>
</tr>
uploads.js
jQuery(document).ready(function($){
function dynamic_image( button , textbox )
{
var custom_uploader;
$(button).click(function(e) {
e.preventDefault();
//If the uploader object has already been created, reopen the dialog
if (custom_uploader) {
custom_uploader.open();
return;
}
//Extend the wp.media object
custom_uploader = wp.media.frames.file_frame = wp.media({
title: 'Choose Image',
button: {
text: 'Choose Image'
},
multiple: false
});
//When a file is selected, grab the URL and set it as the text field's value
custom_uploader.on('select', function() {
attachment = custom_uploader.state().get('selection').first().toJSON();
$(textbox).val(attachment.url);
});
//Open the uploader dialog
custom_uploader.open();
});
}
dynamic_image('#upload_image_button' , '#upload_image');
dynamic_image('#section2_1' , '#section2_text1');
dynamic_image('#section2_2' , '#section2_text2');
dynamic_image('#section2_3' , '#section2_text3');
dynamic_image('#section2_4' , '#section2_text4');
dynamic_image('#section2_5' , '#section2_text5');
});
script
<script type="text/javascript">
$(document).ready(function(){
var counter = 2;
$("#addButton").click(function () {
if(counter>5){
alert("Only 5 components are allowed");
return false;
}
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
var newDescDiv = $(document.createElement('div'))
.attr("id", 'DescDiv' + counter);
var newImageDiv = $(document.createElement('div'))
.attr("id", 'ImageDiv' + counter);
newTextBoxDiv.after().html('<label>Title #'+ counter + ' : </label>' +
'<input type="text" name="textbox' + counter +
'" id="title' + counter + '" value="" >');
newDescDiv.after().html('<label>Description #'+ counter + ' : </label>' +
'<input type="text" name="descbox' + counter +
'" id="desc' + counter + '" value="" ><br></br>');
newImageDiv.after().html('<input class="button" type="button" name="upload_s2_' + counter +
'" value="Upload Image" id="section2_' + counter + '" >');
newImageDiv.appendTo("#TextBoxesGroup");
newTextBoxDiv.appendTo("#TextBoxesGroup");
newDescDiv.appendTo("#TextBoxesGroup");
counter++;
});
$("#removeButton").click(function () {
if(counter==1){
alert("No more component to remove");
return false;
}
counter--;
$("#TextBoxDiv" + counter).remove();
$("#DescDiv" + counter).remove();
$("#ImageDiv" + counter).remove();
});
$("#getButtonValue").click(function () {
var msg = '';
for(i=1; i<counter; i++){
msg += "\n Textbox #" + i + " : " + $('#textbox' + i).val();
}
alert(msg);
});
});
</script>
Other button(like #section2_2, #section2_3 ...) maybe not exist, When function dynamic_image run.
Then below code cannot have meaning.
dynamic_image('#section2_2' , '#section2_text2');
// cannot find #section2_2 , because not yet added
Try this.
// function is called when input.button(like #section2_1, #section2_2 ...) on #TextBoxesGroup clicked
$('#TextBoxesGroup').on('click','input.button',function(e){
e.preventDefault();
//If the uploader object has already been created, reopen the dialog
if (custom_uploader) {
custom_uploader.open();
return;
}
//Extend the wp.media object
custom_uploader = wp.media.frames.file_frame = wp.media({
title: 'Choose Image',
button: {
text: 'Choose Image'
},
multiple: false
});
//When a file is selected, grab the URL and set it as the text field's value
custom_uploader.on('select', function() {
attachment = custom_uploader.state().get('selection').first().toJSON();
$(textbox).val(attachment.url);
});
//Open the uploader dialog
custom_uploader.open();
})
See example
indicate actually like following
$('#TextBoxesGroup').on('click','input.button',function(e){
var $clickedInput = $(this);// JQuery Object of section2_2
var clickedInputId = $clickedInput.attr('id'); // section2_2
var indicateKey = clickedInputId.substring(10,clickedInputId.length);// 2
var neededTextId = 'section2_text'+indicateKey ; //section2_text2
var $neededText = $("#" +neededTextId ); // JQuery Object of section2_text2
// run logic what you want to do
})

Categories

Resources