I have a table where each row contains some data (data-id) and a <div class = "upload">Upload</div>. The uploader needs to be passed an object which contains uploader_obj.button set as the initiating <div>, any parameters such as data-id to be sent to the server, and a bunch of other stuff which I didn't show.
The following script loops over the table, modifies the object to set button and params.id, and creates the uploader on each row.
While a separate upload button is created on each row, they each reference the same params.id which is set to the last row's value (i.e. 222). I need each to be set to the value of their specific row.
One way to fix it is to have each uploader have it's own upload_obj, but this seems like a waste of memory.
Instead, I tried to reference data-id within the uploader_obj. I can do so within onSubmit, however, haven't figured out how to use this value to set param.id. I've tried to set it within param by doing something like params: {'id':$(this.button).parent().parent().data('id')} but this is my document, and not the uploader.
So... Without making a separate uploader_obj for each row, how could I make each row's uploader sent its own param.id to the server? Thank you
PS. Sorry for the weak title. I really tried to think of a better one but couldn't.
<table>
<tr data-id="123"><td>Hello</td><td><div class="upload">Upload</div></td></tr>
<tr data-id="321"><td>Hello</td><td><div class="upload">Upload</div></td></tr>
<tr data-id="222"><td>Hello</td><td><div class="upload">Upload</div></td></tr>
</table>
var uploader_obj = {
button:null,
params: {'id':null},
onSubmit: function(id, fileName) {
var id=$(this.button).parent().parent().data('id')
console.log(id);
},
otherStuff: whatever
};
$('#myTable div.upload').each(function(i,v){
uploader_obj.button=this;
uploader_obj.params.id=$(this).parent().parent().data('id');
new qq.FileUploaderBasic(uploader_obj);
});
You're passing the same object in every iteration, just create the object from the values you have inside the loop instead:
$('#myTable div.upload').each(function(i,ele){
new qq.FileUploaderBasic({
button: ele,
params: {
id: $(ele).closest('tr').data('id')
},
onSubmit: function(id, fileName) {
var id=$(this).closest('tr').data('id')
},
otherStuff: whatever
});
});
I think the problem is that you never create a new object of "uploader_obj". So on every loop-iteration you are overwriting the values of your object.
edit:
var a = new Object();
$('#myTable div.upload').each(function(i,v){
a[i] = uploader_obj;
a[i].button=this;
a[i].params.id=$(this).parent().parent().data('id');
new qq.FileUploaderBasic(a[i]);
});
Instead of making uploader object as a global variable, if you make it local varaible to qq.FileUploaderBasic function and send button_object and data_id as a parameter, may be it will work.
you can try like
$('#myTable div.upload').each(function(i,v){
var button=this;
var id=$(this).parent().parent().data('id');
new qq.FileUploaderBasic(button,id);
});
and keep your object inside your function.
Related
Is there a way to trigger a function from within a rowFormatter? I'm using the responsiveLayout: "collapse"-option, and I really like it.
However, I would like to trigger the toggleList function (or what's it's called.... 1 from '19)
I would like to not go the .click() way, so I created my own (rip-off) solution within the rowClick:
let isOpen = row._row.modules.responsiveLayout.open;
var collapseEl = row._row.element.querySelector('div.tabulator-responsive-collapse');
if (!(isOpen)) {
collapseEl.classList.add("open");
if (collapseEl) {
collapseEl.style.display = '';
}
} else {
collapseEl.classList.remove("open");
if (collapseEl) {
collapseEl.style.display = 'none';
}
}
row._row.modules.responsiveLayout.open = !(isOpen);
But... There must be a good way to trigger toggleList(), instead of writing a rip-off function, which doing the same thing...
I've tried to look through the values and functions in row._row, with no luck. I'm 99.7% sure that I missed this part in the documentation........ But I've really tried to search the best I could.
TL;DR: I would like to trigger the toggleList() function defined within formatter, in my rowClick() event-function. Is that possible?
There is no toggleList function built into Tabulator.
In the example you reference there it is simply a function called toggleList that is defined inside the row formatter and triggered when an element added by the row formatted is clicked.
Because the toggleClick function is defined inside the row formatter its scope is limited to that formatter function so it cannot be accessed from outside it.
one way to get around this would be to assign the function to a property on the row data object then you could access it from else where in the table.
So if we take the example you provided a link to and at the top of the customResponsiveCollapseFormatter function add the following:
var data = cell.getData(); //retrieve the row data object
Yhen where we define the toggleList function, instead of the simple function definition we can assign it to a property on the data object, lets call it collapseToggle, we will also tweak it so it dosnt need the isOpen property passed in and insted flips the state of the open variable itself, that way it can be called from anywhere outside the formatter without knowledge of the current state:
data.collapseToggle = function toggleList(){
open = !open;
Then in our cellClick function we can check to see if the collapseToggle property is defined on the row data and then call it:
cellClick:function(e, cell){
var data = cell.getData();
if(data.collapseToggle){
data.collapseToggle();
}
}
I'm new to JQuery and I'm trying to define a JQuery function with the purpose of edit a table row: a modal asks for the new values and then, the function update the table row content. But when I select the row I want to edit, the variable in which the row was stored "accumulates" all the previous rows that have been edited in the same object and when I try to update the new values to this single row, all the rows edited before receive and show the same value. Why is this happening?
I'll show you the code:
$("#table").on("click", ".edit", function() {
var table = $("#table").DataTable();
var row = $(this).closest("tr");
//getting the <tr> content with Datatables API:
var values = $table.row(row).data();
$("#name").val(values[0]);
$("#surname").val(values[1]);
$("#city").val(values[2]);
$("#myModal .modal-footer").on("click", "#confirm", function() {
var newValues = []
//getting the <tr> content with Datatables API:
//this alert appears as many time as many rows have been changed
alert($table.row(row).data());
//deleting the old data from the server...
//getting the new values:
newValues.push($("#name").val());
newValues.push($("#surname").val());
newValues.push($("#city").val());
//adding the new date to the server...
$("#myModal").modal("hide");
//update the html table:
table.row(row).data([newValues[0], newValues[1], newValues[2]]);
});
});
As I've explained before, the variable "row" in the .on("click")
function "accumulates" all the rows that have been edited before.
I thought it was a scope probelm, so I've also tried to call an extern function which basically did the same things and took advantage of the event.data object:
$("#confirm").on("click", {table: table, row: row}, edit);
but with no luck. If any one can help me or even provide me some advice or documentation, it would be very appreciated.
You have to use two different and independent functions using an external variable to connect them; you can't use .on() in a nested way
I'm trying to get data used in my table to be used in a div when I click on the table. The thing is, there are multiple tables in my script according to the data of my JSON. So my JSON consists of object that consists of object. For example:
My table(s) are rendered like this:
data.forEach(function(somedata){
return '<table><tr><td>'+somedata.something+'</td></tr></table>';
});
Now I've tried to get the onclick to work in this case but I cant seem to figure out how. I'd like to not use specific ID's rendered in the foreach like:
var i=0;
data.forEach(function(somedata){
i++;
return '<table id="'.id.'"><tr><td>'+somedata.something+'</td></tr></table>';
});
the variable somedata consists of an object so I cant just make an onclick in the html code of the table either and send the data in it.
So somedata would look something like this but json encoded:
somedata{
[0]=>array(
'something'=>'test',
'theobject'=>array(...)
),
[1]=>array(etc...)
}
Now what I want is to get the data from theobject in a seperate div as soon as I click on the table that belongs to the right somedata.
I've been thinking of making a jquery on click for this but then I would need specific ID's in the table(if that's the only possible solution then I'd take it). Cant I do something with this or something? Or send the data at the same time it's being rendered cause in my code I can at the moment of course reach to somedata.theobject
I think I'm thinking a bit too difficult about this. Am I?
You can pass this in onclick function like
return '<table onclick=makeObject(this)><tr><td>'+somedata.something+'</td></tr></table>';
And then use the function to get the data
function makeObject(that){
var tbl = $(that).find('tr').map(function() {
return $(this).find('td').map(function() {
return $(this).html();
}).get();
}).get();
}
There are a few ways to go about this. Rather than using the forEach function we can use the jQuery.map function, since you've indicated that you're open to using jQuery :-)
var $els = $.map(data, function(somedata, i){
var $el = $('<table><tr><td>'+somedata.something+'</td></tr></table>')
.click(function(e) {
populateDivWithData(somedata.theobject);
});
return $el;
});
The call to .click inside each will create a separate click handler for each item in data; each click handler then has access to the relevant theobject value.
EDIT: Thanks #Loko for the reminder about the .forEach built-in
I'm trying to write a plugin-like function in jQuery to add elements to a container with AJAX.
It looks like this:
$.fn.cacheload = function(index) {
var $this = $(this);
$.get("cache.php", {{ id: index }).done(function(data) {
// cache.php returns <div class='entry'>Content</div> ...
$(data).insertAfter($this.last());
});
}
and I would like to use it like this:
var entries = $("div.entry"),
id = 28;
entries.cacheload(id);
Think that this would load another "entry"-container and add it to the DOM.
This is works so far. But of course the variable that holds the cached jQuery object (entries) isn't updated. So if there were two divs in the beginning and you would add another with this function it would show in the DOM, but entries would still reference the original two divs only.
I know you can't use the return value of get because the AJAX-call is asynchronous. But is there any way to update the cached object so it contains the elements loaded via AJAX as well?
I know I could do it like this and re-query after inserting:
$.get("cache.php", {{ id: num }).done(function(data) {
$(data).insertAfter($this.last());
entries = $("div.entry");
});
but for this I would have to reference the variable holding the cached objects directly.
Is there any way around this so the function is self-contained?
I tried re-assigning $(this), but got an error. .add() doesn't update the cached object, it creates a new (temporary) object.
Thanks a lot!
// UPDATE:
John S gave a really good answer below. However, I ended up realizing that for me something else would actually work better.
Now the plugin function inserts a blank element (synchronously) and when the AJAX call is complete the attributes of that element are updated. That also ensures that elements are loaded in the correct order. For anyone stumbling over this, here is a JSFiddle: http://jsfiddle.net/JZsLt/2/
As you said yourself, the ajax call is asynchronous. Therefore, your plugin is asynchronous as as well. There's no way for your plugin to add the new elements to the jQuery object until the ajax call returns. Plus, as you discovered, you can't really add to the original jQuery object, you can only create a new jQuery object.
What you can do is have the plugin take a callback function as a second parameter. The callback could be passed a jQuery object that contains the original elements plus the newly inserted ones.
$.fn.cacheload = function(index, callback) {
var $this = this;
$.get('cache.php', { id: index }).done(function(html) {
var $elements = $(html);
$this.last().after($elements);
if (callback) {
callback.call($this, $this.add($elements));
}
});
return $this;
};
Then you could call:
entries.cacheload(id, function($newEntries) { doSomething($newEntries); } );
Of course, you could do this:
entries.cacheload(id, function($newEntries) { entries = $newEntries; } );
But entries will not be changed until the ajax call returns, so I don't see much value in it.
BTW: this inside a plugin refers to a jQuery object, so there's no need to call $(this).
I'm trying to use the Ajax File Upload as featured here: http://valums.com/ajax-upload/
As you can see, I need to create a qq.FileUploader object to initialize the script. However, I need to be able to dynamically create this objects without knowing the IDs of the elements. I've tried creating something like this:
var uploader, i = 0;
$(".file-upload").each(function() {
$e = $(this);
i++;
uploader[i] = new qq.FileUploader({
element: $(this)[0],
action: 'uploadfile.php',
allowedExtensions: ['doc', 'docx', 'pdf'],
multiple: false,
onComplete: function(id, fileName, responseJSON) {
$($e).siblings('input').val(responseJSON.newfilename);
}
});
});
I've learned that the [i] part I have added breaks the script, because I cannot have objects inside of an array.
Is there another way I can create this objects dynamically? They need to all have a unique name, otherwise the onComplete function gets overwritten for all of them. I experimented with using eval(), but I can't seem to make it work correctly.
You have to declare uploader as an array first :
var uploader = [];
Because you declared the variable without defining it, it has the default value of undefined , and your code was translated into something like undefined[i] which triggers an error.
Has to be something like
var uploader = {};
or else uploader is null and you cannot assign anything to it.
EDIT:
So there're two opitions, in my opinion, if one wants to have an array than it makes sense to declare one, var uploader = []; and then use the uploader.push() method or define it as an object var uploader = {}; and just do uploader[i] = ....
It is also possible to do the latter with an a array, but in the latter case I see no point in maintaining the counter (i).