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/
Related
I have a input box. I enter the search term and the values get returned. What I am trying to do is click the dynamic button with the value attached to it. However when I click on the button it reloads the page instead of showing an alert box. This only happens with the dynamic button not the searchButton
$(document).ready(function () {
$('.cta-button').click(function () {
event.preventDefault();
alert("You clicked the button");
});
$('#searchButton').click(function () {
event.preventDefault();
var varSearch = $('#searchDB').val();
if (!varSearch) {
$('#result').html("Please enter a search term");
return;
}
$.ajax({
contentType: "application/json; charset=utf-8",
data: 'ID=' + varSearch,
url: "getTest.ashx",
dataType: "json",
success: function (data) {
var result = '';
$.each(data, function (index, value) {
result += '' +
'<div class="main-area bg-white">' +
'<div class="row">' +
'<div class="medium-6 columns">' +
'<button type="submit" id="OfferID_' + index + '" class="cta-button cta-button-icon">Add to Cart</button>' +
'<br />' +
'</div>' +
'</div>' +
'</div>'
});
if (!result) {
result = 'No data were found for ' + varSearch;
};
$('#result').html(result);
}
});
});
});
<section>
<div class="row">
<div class="medium-4 columns medium-centered">
<div class="search-rewards">
<input type="search" id="searchDB" />
<button type="submit" id="button" class="button"></button>
</div>
</div>
</div>
<div class="row">
<div class="medium-6 columns medium-centered">
<div id="result">
</div>
</div>
</div>
</section>
You're missing the event argument to your click functions. Without it, event.preventDefault() does nothing.
$('.cta-button').click(function(event) {
event.preventDefault();
alert("You clicked the button");
});
Update
To bind to dynamic buttons, you'd need to use a delegate as #MACMAN suggested:
$(document).on('click', '.cta-button', null, function(event){
event.preventDefault();
alert("You clicked the button");
});
Use delegate to assign the click property to the dynamic button.
Sometimes JQuery events not working for dynamically generated elements. You can use JQuery.on() for dynamically generated elements.
http://api.jquery.com/on/
try using this
$('.cta-button').on("click", (function() {
event.preventDefault();
alert("You clicked the button");
});
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 .
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'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
how to create a dynamic button with respect to XML data.Here i have to convert the name (XYZ) to a button and making an event to each dynamic button.Now am getting xyz,50 but i want to change it as button with name xyz,and also events.
<class_members>
<student>
<name>XYZ</name>
<marks>50</marks>
</student>
<student>
<name>ABC</name>
<marks>25</marks>
</student>
</class_members>
jquery code is here.
<script>
$(document).ready(function () {
$("#Submit").click(function () {
$.ajax({
type: "GET",
url: "marks.xml",
dataType: "xml",
success: function (xml) {
$(xml).find('student').each(function () {
var Name = $(this).find('name').text();
var Mark = $(this).find('marks').text();
$("#content").append('<li>' + Name + " ," + Mark + '<li>');
});
}
});
});
});
</script>
</head>
<body>
<form id="From1" method="post">
<input type="button" value="submit" name="Submit" id="Submit" />
<div id="content">
</div>
</form>
add button with some class and attach event using that class, like, change:
$("#content").append('<li>' + Name + " ," + Mark + '<li>');
to
$("#content").append("<li><input type='button' class='dyna_btn' value='"+Name+"' /></li>");
and attach event to these buttons:
$(document).on("click", ".dyna_btn", function() {
//do something here
console.log("button clicked");
});