Getting attribute of jQuery Dropzone DIV - javascript

I have dropzone (v3.7.1) divs in each of my bootstrap tabs.
How can I upload all files in all dropzones only after clicking on submit button (not using form for each dropzone)? When I set autoProcessQueue to false and try to attach listener, an error saying unable to attach an event to undefined shows up...
How do I get attributes of a dropzone object e.g. rel="6" of the first dropzone? Attempts to use this.attr('rel') / $(this).attr('rel') results in 'undefined'...
HTML
<form class="my-form" method="post">
<input type="text" name="form-input-1" id="form-input-1" />
<input type="text" name="form-input-2" id="form-input-2" />
<div class="tab-content">
<div class="tab-pane active" id="ic_6">
<h3>Overview</h3>
<div rel="6" class="dropzone" id="my-dropzone"></div>
</div>
<div class="tab-pane" id="ic_1">
<h3>Living Room</h3>
<div rel="1" class="dropzone" id="my-dropzone"></div>
</div>
<div class="tab-pane" id="ic_2">
<h3>Kitchen</h3>
<div rel="2" class="dropzone" id="my-dropzone"></div>
</div>
<div class="tab-pane" id="ic_3">
<h3>Bathroom</h3>
<div rel="3" class="dropzone" id="my-dropzone"></div>
</div>
<div class="tab-pane" id="ic_4">
<h3>Bedroom</h3>
<div rel="4" class="dropzone" id="my-dropzone"></div>
</div>
<div class="tab-pane" id="ic_5">
<h3>Outdoors</h3>
<div rel="5" class="dropzone" id="my-dropzone"></div>
</div>
</div>
<button type="submit">Submit</button>
</form>
JS
Dropzone.options.myDropzone = {
url: "upload.php",
maxFilesize: 2, // MB
addRemoveLinks: true,
acceptedFiles: "image/*",
accept: function(file, done) {
console.log("uploaded");
done();
},
init: function() {
this.on("addedfile", function(file) {
//== divider ==//
var dividerElement = Dropzone.createElement("<div> </div>");
file.previewElement.appendChild(dividerElement);
//== caption input : still trying to figure capturing this ==//
var captionInput = Dropzone.createElement("<input type='text' name='caption' maxlength='50' placeholder='Enter a caption' />");
file.previewElement.appendChild(captionInput);
});
this.on("removedfile", function(file) {
$.ajax({
url: "delete_temp_files.php",
type: "POST",
data: { filename: file.name }
});
});
}
}

I know this is an old post, but the solution to accessing attributes on the original element is
console.log($($(this)[0].element).attr("rel"));

If your html code is:
<div class="dropzone" data-name="mypics"></div>
pure javascript:
new Dropzone("div.dropzone", {
url: "<backend-url>",
success: function (file, response) {
// Get "data-name" attribute here
var name = this.element.getAttribute("data-name");
}
});

Related

Dropzone.js how to add hidden input with value to uploaded image

I am having problems with adding hidden input field to uploaded images using dropzone.js.
What i am trying to do is to use dropzonejs to upload images to the website and then having possibility with jquery sortable to drag and change order of the images.
I've managed to make it working everything so far except when i use separated input array the order of the images is not changed on drag and drop.
For this to work i need to find a way to add hidden input to the image template when image is uploaded.
Here is the code i use in .php file
<div class="form-group">
<div id="media-uploader" class="dropzone"></div>
<div id="uploaded-media" class="hidden">
</div>
</div>
Right now when image is uploaded a hidden input field is added to #uploaded-media but i need to change that and add hidden input in uploaded image template holder.
Here is what it looks like now when image is uploaded
<div id="media-uploader" class="dropzone dz-clickable ui-sortable dz-started">
<div class="dz-default dz-message">
<span>Drop files here to upload</span>
</div>
<div class="dz-preview dz-processing dz-image-preview dz-success dz-complete">
<div class="dz-image"><img data-dz-thumbnail="" alt="DSC_3771-Edit.jpg" src=""></div>
<div class="dz-details">
<div class="dz-size"><span data-dz-size=""><strong>0.9</strong> MB</span></div>
<div class="dz-filename"><span data-dz-name="">DSC_3771-Edit.jpg</span></div>
</div>
<div class="dz-progress">
<span class="dz-upload" data-dz-uploadprogress="" style="width: 100%;"></span>
</div>
<div class="dz-error-message"><span data-dz-errormessage=""></span></div>
<div class="dz-success-mark"> </div>
<div class="dz-error-mark"> </div>
<a class="dz-remove" href="javascript:undefined;" data-dz-remove="">Remove file</a>
</div>
</div>
The only small change i need is it to look like this
<div id="media-uploader" class="dropzone dz-clickable ui-sortable dz-started">
<div class="dz-default dz-message">
<span>Drop files here to upload</span>
</div>
<div class="dz-preview dz-processing dz-image-preview dz-success dz-complete">
<div class="dz-image"><img data-dz-thumbnail="" alt="DSC_3771-Edit.jpg" src=""></div>
<div class="dz-details">
<div class="dz-size"><span data-dz-size=""><strong>0.9</strong> MB</span></div>
<div class="dz-filename"><span data-dz-name="">DSC_3771-Edit.jpg</span></div>
</div>
<div class="dz-progress">
<span class="dz-upload" data-dz-uploadprogress="" style="width: 100%;"></span>
</div>
<div class="dz-error-message"><span data-dz-errormessage=""></span></div>
<div class="dz-success-mark"> </div>
<div class="dz-error-mark"> </div>
<a class="dz-remove" href="javascript:undefined;" data-dz-remove="">Remove file</a>
**<input type="hidden" name="media-ids[]" id="media-ids[]" class="media-ids" value="812">**
</div>
</div>
Here is the dropzone configuration
// Dropzone file uploader
Dropzone.autoDiscover = false;
var myDropzone = new Dropzone ("#media-uploader", {
url: dropParam.upload,
autoProcessQueue: true,
parallelUploads: 1,
uploadMultiple: false,
maxFilesize: 3,
acceptedFiles: 'image/*',
addRemoveLinks: true,
maxFiles: 10,
success: function (file, response) {
file.previewElement.classList.add("dz-success");
file['attachment_id'] = response; // push the id for future reference
$('#uploaded-media').append( $('<input type="hidden" name="media-ids[]" id="media-ids[]" class="media-ids" value="' + response +'">') );
},
error: function (file, response) {
file.previewElement.classList.add("dz-error");
},
// update the following section is for removing image from library
removedfile: function(file) {
var attachment_id = file.attachment_id;
jQuery.ajax({
type: 'POST',
url: dropParam.delete,
data: {
media_id : attachment_id
}
});
$('input.media-ids[type=hidden]').each(function() {
if ($(this).val() == attachment_id) {
$(this).remove();
}
});
var _ref;
return (_ref = file.previewElement) != null ? _ref.parentNode.removeChild(file.previewElement) : void 0;
}
});
I found the solution, the code below will add an input field to each uploaded image upon successful upload
myDropzone.on("success", function(file, response) {
$(file.previewElement).append( $('<input type="hidden" name="media-ids[]" id="media-ids[]" class="media-ids dz-media-id" value="' + response +'">') );
});
$("div#js-dropzone").dropzone({
url: "/api/mmm/orders/fileupload",
method: 'POST',
maxFilesize: 5, // MB
previewTemplate: previewTemplate,
success: function (response) {
$(response.previewElement).append('<input type="hidden" name="fileupload" value="' + JSON.parse(response.xhr.response).fileName + '" />');
}
});

image show in modal by croppie.js library

I am using croppie.js library to crop a image in modal and save via ajax in database.
It is working when input type file. But do not need it after click on file type. I have an img tag with src and when I click on this image then related image should be in modal and I can crop image.
My img tag is:
<img src="pic1.jpg" id="profilenewpic" width="auto" height="140px" />
When I click on this image then my croppie libraray should work.
<script type="text/javascript">
// start profile crop
$(document).ready(function(){
$image_crop = $('#image_demo').croppie({
enableExif: true,
viewport: {
width:230,
height:230,
type:'square' //circle
},
boundary:{
width:300,
height:300
}
});
$('#profilenewpic').on('click', function(){
var reader = new FileReader();
reader.onload = function (event) {
$image_crop.croppie('bind', {
url: event.target.result
}).then(function(){
console.log(event.target.result);
});
}
reader.readAsDataURL(this.files[0]);
$('#uploadimageModal').modal('show');
});
$('.crop_image').click(function(event){
$image_crop.croppie('result', {
type: 'canvas',
size: 'viewport'
}).then(function(response){
$.ajax({
url:"../../upload.php",
type: "POST",
data:{"image": response},
success:function(data)
{
$('#uploadimageModal').modal('hide');
$('#profile_id').hide();
$('#show_image').attr('src', data);
$('#show_image').show();
}
});
})
});
});
// end profile crop
</script>
My modal is:
<div id="uploadimageModal" class="modal" role="dialog">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
<div class="modal-body">
<div class="row">
<div class="col-md-8 text-center">
<div id="image_demo" style="width:350px; margin-top:30px"></div>
</div>
<div class="col-md-4" style="padding-top:30px;">
<br />
<br />
<br/>
<button class="btn btn-success crop_image">Crop & Upload Image</button>
</div>
</div>
</div>
</div>
</div>
</div>

knockout carrying the data to Multiple View

Below is my code which is knocokout js,i have ListviewModel which is related to two views 1st and second view as below,Both views using the class name UserDetailsView, i am binding two views 1st and second view as below,my problem is, i have click event on the 1st view "Userview" i need to get data of clicked event which is $root.UserView, when i click this it should get all related value and pass to second view so i can bind the data using knockout js ,i am getting the value but unable to bind the data when i clicked $root.UserView so i used jquery in second view for binding, but Now requirement is changed i need make another click event in second view so i can carry data to another view,before that i need to bind the second view with Knockout js how it can be done need help
function ListviewModel()
{
var self = this;
self.Listarray = ko.observableArray();
self.getUserList = function () {
var ListModel = {
userId: UserID
}
jQuery.support.cors = true;
$.ajax({
type: "POST",
dataType: "json",
contentType: 'application/json; charset=utf-8',
data: JSON.stringify(ListModel),
url: serverUrl + 'xxx/xxx/xxx',
success: function (data) {
self.Listarray($.map(data, function (item) {
return new Listdata(item);
}));
}
});
};
//Click Function for UserPersonalview
self.UserView = function (Listarray) {
$("#userId").text(Listarray.userIdId());
$("#userName").text(Listarray.UserName())
document.getElementById('userProfilePic').setAttribute('src', "data:" + Listarray.ProfilePictype() + ";base64," + Listarray.ProfilePicBase64());
window.location.href = "#UserPersonalview";
}
self.UserProfile = function () {
console.log(self.Listarray());
}
}
//Model
function Listdata(data)
{
var self = this;
self.userId = ko.observable(data.userId);
self.userName = ko.observable(data.userName);
self.userProfilePicBase64 = ko.observable(data.userProfilePicBase64);
self.userProfilePictype = ko.observable(data.userProfilePictype);
self.userProfilepic = ko.computed(function () {
return "data:" + self.userProfilePictype() + ";base64," + self.userProfilePicBase64();
});
}
//1st View
<div data-role="view" id="Userview" class="UserDetailsView" data-layout="default">
<div data-role="content" style="background-color:#fff!important">
<div>
<ul style="list-style: none;" data-role="listview" id="hierarchical-listview" data-bind="foreach:Listarray">
<li style="background-color:#FFF" data-bind="click:$root.UserView">
<div style="width:100%;">
<div style="width:50%;float:left">
<span data-bind="text:$data.userId" style="display:none"></span>
<img data-bind="attr: { src:$data.userProfilepic }" onclick="Imagepopover()" />
<label style="width: 25%!important;" class="firendslisttext" data-bind="text:$data.userName"></label>
</div>
<div style="width:50%;float:left;margin: 0px -20px;">
</div>
</div>
</li>
</ul>
</div>
</div>
</div>
//second View
<div data-role="view" id="UserPersonalview" >
<header data-role="header">
<div data-role="navbar" class="UserDetailsView">
<div class="content-header ">
<ul style="list-style: none;" >
<li data-bind="click:$root.UserProfile">
<div class="km-leftitem">
</div>
<div class="block2" >
<div class="inner" style="float:left" >
<span id="userId" style="display:none"></span>
<img data-responsive="" width="40" height="40" id="userProfilePic" src="" style="border-radius: 50%;" />
</div>
<div class="inner" style="float:left;margin-left:15px">
<label id="userName" style="width: 100%!important;"></label>
</div>
</div>
<div class="km-rightitem">
<a data-align="right"><img src="images/icon-add.png" style="height:50px" /></a>
</div>
</li>
</ul>
</div>
</div>
</header>
<div data=role="content"><div>
</div>

Problems displaying dataTable in modal in html partial view

I asked a question here yesterday about this issue but got downvoted, probably because I didn't include any code which is understandable.
Hopefully this question will be more complete and allow you to help me more easily.
So I have 3 views in play:
StudentsList
Script
#{
ViewBag.Title = "StudentsList";
Layout = "~/Views/Shared/_LayoutM.cshtml";
}
#Scripts.Render("~/Scripts/charts")
#Styles.Render("~/Content/formsaltcss")
#model Mvc.Models.StudentViewModel
<script type="text/javascript">
$(document).ready(function () {
$('#AddStudentData').click(function () {
var type = 'student';
var id = 0;
$('#holderArea').html('');
if (!$('#studentDropDown option:selected').length) {
ToastrWarning('Please select a student before running the report');
return;
}
id = $('#studentDropDown').val();
var data = { id: id };
$.ajax({
url: '/Student/StudentAnalysisFiltered',
async: false,
data: data,
dataType: 'html',
success: function (data) {
$('#holderArea').html(data);
}
});
});
});
Relevant HTML
<div class="panel panel-default">
<div class="panel-heading">
<h3 class="margin-bottom0 text-center">Student Analysis</h3></div>
<div class="panel-body">
<div class="row">
<div class="col-sm-12">
<form class="form-horizontal">
<div class="form-group">
<div class="row">
<label class="col-sm-2 control-label">Student Name</label>
<div class="col-sm-4">
#Html.DropDownListFor(c => c.Students, new SelectList(Model.Students, "StudentID", "Name"), "Choose Student"
, new { id = "studentDropDown", #class = "form-control input-sm", data_width = "100%" })
</div>
<div class="col-sm-offset-2 col-sm-10">
<button id="AddStudentData" type="button" class="btn btn-sm btn-primary">Select</button>
</div>
</div>
</div>
</form>
</div>
</div>
</div>
</div>
<div id="holderArea">
</div>
StudentAnalysisSelected
Script
#using Data
#using Mvc.Helpers
#model Mvc.Models.StudentViewModel
#Scripts.Render("~/Scripts/datatables")
<script>
function StudentScoresModal(studentID, answer, result) {
$('#scoresTable').hide();
$('#scoresSpinner').show();
$('#scoresModal').modal('show');
var testID = #Html.Raw(Model.testID );
$.ajax({
cache: false,
url: "/Student/StudentScoresDrillthrough",
data: { 'studentID': studentID, 'answer': answer, 'result': result, 'testID': testID},
success: function (data) {
$('#scoresTable').html(data);
$('#scoresTable').show();
$('#scoresSpinner').hide();
},
error: function () {
toastr.options.positionClass = 'toast-bottom-right';
toastr.options.backgroundpositionClass = 'toast-bottom-right';
toastr.options.timeOut = 3000;
toastr.error('Unable to get student results.');
}
});
}
</script>
Relevant HTML
<div id="holderArea">
<button type="button" class="btn btn-sm btn-primary" onclick="StudentScoresModal(id, '', '')" id="#q.StudentID">View Scores</button>
</div>
<div class="modal in modal-stack" id="scoresModal" aria-hidden="false">
<div class="modal-dialog modal-lg">
<div class="modal-content">
<div class="modal-header">
<h4 class="modal-title"><strong>Student Scores</strong></h4>
</div>
<div class="modal-body">
<div class="row">
<div class="col-xs-12">
<div class="table-responsive" id="scoresTable" style="display:none">
</div>
<div class="sk-cube-grid absolute-center top-85" id="scoresSpinner" style="display:none">
<div class="sk-cube sk-cube1"></div>
<div class="sk-cube sk-cube2"></div>
<div class="sk-cube sk-cube3"></div>
<div class="sk-cube sk-cube4"></div>
<div class="sk-cube sk-cube5"></div>
<div class="sk-cube sk-cube6"></div>
<div class="sk-cube sk-cube7"></div>
<div class="sk-cube sk-cube8"></div>
<div class="sk-cube sk-cube9"></div>
</div>
</div>
</div>
</div>
<div class="modal-footer">
<button type="button" class="btn btn-sm btn-default" data-dismiss="modal">Close</button>
</div>
</div>
</div>
</div>
StudentScoresPartial
Script
<script>
$(document).ready(function () {
$('#studentScores').dataTable({
"data": #Html.Raw(Model.StudentScoresJson),
"columns":[
{ "sName": "StudentID" },
{ "sName": "Answer" },
{ "sName": "Result" }
]
});
});
</script>
HTML
<table id="studentScores" class="display table table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th>StudentID</th>
<th>Answer</th>
<th>Result</th>
</tr>
</thead>
<tfoot>
<tr>
<th>User</th>
<th>Answer</th>
<th>Response</th>
</tr>
</tfoot>
<tbody></tbody>
</table>
How it all works
On the 'StudentsList' view there is a dropdown with list of students, and a 'Select' button to filter on an individual. OnClick this clears the holderArea div and passes studentID to the controller method, which returns a partial view 'StudentAnalysisSelected' and places it inside the holderArea div.
Now a graph is loaded with details specific to the indivudual. When clicked the 'scoresTable' is hidden and the modal is shown and an ajax call is made to StudentScoresDrillthrough controller, which returns the 'StudentScores' partial that is placed into the html of 'scoresTable'.
The problem
Now this all works perfectly first time I filter by student. I click 'Select', the graph loads, I click the graph and the datatable displays neatly in the modal.
However for reasons unknown to me when I click 'Select' again to re-filter, and click on the graph that is loaded all I see is the modal appear with the loading spinner, and it stops there. No errors pertaining to datatables in the console, or anything out of the ordinary for that matter.
I appreciate this is a bit of a read, but i'd be keen to hear any thoughts on what could be causing my issue.
Thanks!
It's because your dom is reloaded and so you loose your event attached.
If you attach ypur event like so, this should do, see doc :
$('#AddStudentData').on('click',function () {});
First try calling dataTable after filter button click using $('#studentScores').dataTable();
If this doesn't work
Instead on your refilter click write:
$('#studentScores').dataTable();
After your partialview is fully loaded. And bind your list in table directly e.g :
StudentID
Answer
Result
#foreeach(var item in Model)
{
item.User
item.Answer
item.Response
}
Finally tracked it down and it was because the modal show was called before the table show.
Thanks to those who posted suggestions, it's much appreciated

How to use javascript to trigger a modal one after another

I want to use the code below to accomplish the following flow:
validate user's input (form in a modal pop up)
if no error, trigger another modal to show something. The content of the result modal comes from an ajax call.
The problem is the result modal never shows.
Edited: The problem seems in relation to e.preventDefault() as I tested with another version which makes the ajax call in $("#frmSchPkg").submit(function(e).
It works with preventDefefalut and doesn't work if preventDefault() is missing.
Perhaps the question is how to add preventDefault() to this posted javascript.
$.validate({
form: '#frmSchPkg',
onSuccess: function($form) {
var pkgnum12 = $("#pkgnum12").val();
var dataString = 'pkgnum12=' + pkgnum12;
$.ajax({
type: "GET",
url: "admin/sch_pkg_c.php",
data: dataString,
cache: false,
async: false,
success: function(data) {
console.log(data);
alert(data); // able to see data being expected. so the ajax call is successful
$('#text-modal').modal('hide'); // tried to comment this out for testing, 1st modal vanishes anyway at this point
$('#LookupResultModal').find('.ct_schpkgresult').html(data);
$('#LookupResultModal').modal('show');
},
error: function(err) {
console.log(err);
}
});
}
});
<div class="modal fade text-modal" id="text-modal" tabindex="-1" role="dialog" aria-labelledby="smallModal" aria-hidden="true" data-backdrop="static" data-keyboard="false">
<div class="modal-dialog modal-sm2">
<div class="modal-content">
<div class="modal-header bg-shop">
<a class="close-modal" href="#" data-dismiss="modal">
<span class="menu-icon"></span>
</a>
<h2 class=""><b>Search</b></h2>
</div>
<form action="" method="post" enctype="multipart/form-data" class="form-horizontal" id="frmSchPkg">
<div class="modal-body">
<div class="form-group">
<div class="col-sm-12">
<input class="form-control" name="pkgnum12" id="pkgnum12" type="text" placeholder="enter tracking number" data-validation="number length" data-validation-length="12-12" />
</div>
</div>
</div>
<div class="modal-footer">
<div class="col-sm-6">
</div>
<div class="col-sm-6">
<button name="btnfind" id="btnfind" type="submit" class="clsfind btn btn-store btn-block">
<i class="fa fa-search"></i> Search</button>
</div>
</div>
</form>
</div>
</div>
</div>
<div class="modal fade" id="LookupResultModal" tabindex="-1" role="dialog" aria-labelledby="LookupResultModal" aria-hidden="true" data-backdrop="static" data-keyboard="false">
<div class="modal-dialog ">
<div class="modal-content">
<div class="modal-header bg-shop">
<a class="close-modal" href="#" data-dismiss="modal">
<span class="menu-icon"></span>
</a>
<h2 class=""><b>Search Result</b></h2>
</div>
<div class="ct_schpkgresult"></div>
</div>
</div>
</div>
The JS script should be like
Ajax method should be inside validation onSuccess: function($form) { }
First modal hide and 2nd modal show should be in side Ajax method success: function(data) { }
$.validate({
form: '#frmSchPkg',
onSuccess: function($form) {
var pkgnum12 = $("#pkgnum12").val();
var dataString = 'pkgnum12=' + pkgnum12;
alert(dataString);
$.ajax({
type: "POST",
url: "admin/sch_pkg_c.php",
data: dataString,
cache: false,
success: function(data) {
console.log(data);
$('#text-modal').modal('hide'); //If all good hide first modal
$('#LookupResultModal').modal('show'); //show 2nd modal
$('#LookupResultModal').find('.ct_schpkgresult').html(data); //show response in 2nd modal
},
error: function(err) {
console.log(err);
}
});
}
});
I found the following solution:
$.validate({
form: '#frmSchPkg',
onSuccess: function(form) {
return $.sendFormDataViaAJAX(form);
}
});
$.sendFormDataViaAJAX = function(form) {
var pkgnum12 = $("#pkgnum12").val();
var dataString = 'pkgnum12=' + pkgnum12;
$.ajax({
type: "GET",
url: "admin/sch_pkg_c.php",
data: dataString,
cache: false,
async: false,
success: function(data) {
console.log(data);
$('#text-modal').modal('hide');
$('#LookupResultModal').find('.ct_schpkgresult').html(data);
$('#LookupResultModal').modal('show');
},
error: function(err) {
console.log(err);
}
});
return false;
};

Categories