Drag and drop not working after adding new row - javascript

I'm using jquery.tablednd.0.7.min.js to drag and drop table rows. When I add new row in table dynamically (i.e. with javascript add row) that new row did not drag n drop. Other rows that are already present in table can be dragged.
I think this new row is not being synched with jQuery drag n drop code.
I am adding new row like this.
This is jquery dragnDrop file code.
On page load I am using this code to assign this functionality to table
$(document).ready(function() {
$("#tableId").tableDnD({
onDragClass : "myDragClass",
onDrop : function(table, row) {
},
onDragStart : function(table, row) {
console.log("drag start");
}
});
});

Just use $("#tableId").tableDnDUpdate()
From the docs:
Will update all the matching tables, that is it will reapply the mousedown method to the rows (or handle cells).
This is useful if you have updated the table rows using Ajax and you want to make the table draggable again.
The table maintains the original configuration (so you don't have to specify it again).

You haven't shown the code which does the appending of the rows, which is where you would need to rebind the tableDnD related events, but it would look something like this:
$(document).ready(function() {
//on load
addTableDnD();
//appending a row
$(".add-row").click(function() {
$("<tr />").appendTo("#tableId");
addTableDnD(); // re-attach events to pick up the new row.
});
});
function addTableDnD() {
$("#tableId").tableDnD({
onDragClass : "myDragClass",
onDrop : function(table, row) {
},
onDragStart : function(table, row) {
console.log("drag start");
}
});
}

As simple as:
$("#tableId").tableDnDUpdate()
after adding that new row.

Please try this:
function sample()
{
$("#tableId").tableDnD({
onDragClass : "myDragClass",
onDrop : function(table, row) {
},
onDragStart : function(table, row) {
console.log("drag start");
}
});
}
Call sample() function in body onload and once again call sample() function in each new row entry time.
Note: To Avoid twice issue please try to use "live" function in jquery

If a newly added row tr has the same id as an existing row, tablednd may not make it dragable.

$("#table_id").tableDnDUpdate();
I solved same issue with this

Related

Tabulator.js: cellClick callback is not fired when clicking a checkbox

I need to recalculate the table by calling recal after a row was selected by check box. If it is selected by clicking the row calling recal works. I copied the below code from plugin site
{formatter:"rowSelection", titleFormatter:"rowSelection", hozAlign:"center", headerSort:false, cellClick:function(e, cell){
console.log("table ",table);
// cell.getRow().toggleSelect();
console.log("table ",table);
table.recalc();
}},
but nothing gets executed. The checkbox gets checked and the row highlighted. You can try my jsFiddle.
UPDATE 1
so it works if I click off the checkbox but I want the function to be triggered when the checkbox is clicked.
As the name suggest cellClick which should be called on cell element click there is another element which is considered cell and checkbox is contained inside cell that's why cellClick is not trigger when you click checkbox and triggered when click outside of checkbox
Issue
As Suggested by #EugeneOlisevich instead of listening to cellClick, Listening to rowSelectionChanged would be better option.
Instead of using table to call recalc as table reference is not created until first load completes.
Another way you can access recalc function is through this
...
rowSelectionChanged: function(e, row) {
this.recalc();
},
...
Issue
When you click editable column if row is selected then it will deselect the row
which can be solve by preventing event bubbling to parent through cellClick function.
...
{
title: "mn",
field: "mn",
editor: "number",
cellEdited: function(cell) {
aktualizuj_m(cell);
},
cellClick: function(e, cell) {
e.preventDefault();
e.stopPropagation();
},
},
...
Issue
As table reference is not created on first load here i added condition to not run loop until table reference is undefined/null
table && values.forEach(function(value, index) {
var row = table.getRow(index + 1);
if (row.isSelected() && value) {
calc = calc + value;
}
});
Issue
If you change mn column input to 0 then sum is not updated
which can be solved by updating condition.
...
if (typeof mnozstvi == "number") {
cell.getRow().update({
cena_m: cena * mnozstvi
});
}
...
Note: Negative range can be input in mn column
Here working example
You can try to use another event handler instead of listening to direct cell click or row selection (or it depends on behaviour you want)
Here is the link to fiddle to check the solution:https://jsfiddle.net/02phqxz8/
...,
rowSelectionChanged:function(data, rows) {
if(table) {
table.recalc();
}
},
...
What was changed:
Instead you can handle rowSelectionChanged event. Every time it is called, by clicking row, or clicking checkbox you can call recalculate for table. Just be sure to check teh table object by default, because the event is fired prior the constuctor return tha table itself.
Or as an option to avoid this additoinal check every time, you can subscribe to this event right after table is created.
You can use rowSelectionChanged
rowSelectionChanged:function(data, rows) {
if (updatedDataLength != data.length) {
updatedDataLength = data.length;
table.recalc();
}
},
var updatedDataLength = 0;
You need to add a local variable that could check data changed because the first time the table rendered, it will also call table.recalc() that will cause a problem of rendering the initial table.
So I suggest using to check updated data length to keep it simple rather than comparing whole data.
Or you can just add a flag var tableRendered = false;.
rowSelectionChanged: function(data, rows) {
if (!tableRendered) {
tableRendered = true;
} else {
table.recalc();
}
},

bind again the sorting capabilities on click button

First, I can disable the sorting in the table headers by just
$("button.disable-sorting").click(function(){
$("table thead th").off("click.DT");
});
now my problem is how to bind back the sorting on the table headers, I tried
$("button.restore-sorting").click(function(){
$("table thead th").bind("click.DT");
});
but seem's not working. Any help ideas on how to bind back the sorting capabilities of the datatables table headers?
PS: im on DataTables 1.10.12
I would store original event listeners right after initilization. In the example below I preserve all events for the very first <th> by saving them to an array map events :
var table = $('#example').DataTable({
initComplete: function() {
$.each($._data($('#example thead th')[0], 'events'), function(name, obj) {
events[name] = obj[0]
})
}
})
Now you have a map of the "native" dataTables events on the form
events['click'] => old event handler
events['keypress'] => old event handler
...
And then it is really simple to turn sorting (and other dataTables event-driven features) on and off for a particular header (or all headers). Here is a small demo with disable / enable buttons :
//remove original event listeners, add alternative
$("#disable").click(function() {
$("#example thead th:nth-child(1)")
.unbind()
.bind('click', function() {
alert('all listeners removed')
})
})
//restore any original event
$("#enable").click(function() {
var $th = $("#example thead th:nth-child(1)")
$th.unbind()
for (var name in events) {
$th.bind(name, events[name])
}
})
demo -> http://jsfiddle.net/8sbcage4/ (disables / enables dataTables events for the first header)

Moving rows to and from Gridviews using .clone, .cloneNode and .append

I have two Gridviews, one loaded with data and the other not. When I double click an item from gvDisplayAvailItems, I want the row to go to gvDisplaySelectedItems, and vice-versa. The Grids are also multi-select, with a button allowing all selected items to be moved. gvDisplaySelectedItems differs by 1 additional input column.
AddDisplayParams() is called when the button is pressed.
function AddDisplayParams() {
var rows = $("#gvDisplayAvailItems").find('tr.selected');
rows.each(function (index, element) {
element.classList.remove("selected");
var newRow = element.cloneNode(true);
newRow.appendChild(customIdTb.cloneNode(true));
$("#gvDisplaySelectedItems").append(newRow);
element.remove();
});
}
AddDisplayParam is called on double-click.
function AddDisplayParam(param) {
var newRow = param.clone(true);
newRow.append(customIdTb.cloneNode(true));
$("#gvDisplaySelectedItems").append(newRow);
param.remove();
}
And here is how I trigger the selection and double clicks.
$("#gvDisplaySelectedItems tr").click(function () {
$(this).toggleClass("selected");
});
$("#gvDisplaySelectedItems tr").dblclick(function () {
RemoveDisplayParam($(this));
});
$("#gvDisplayAvailItems tr").click(function () {
$(this).toggleClass("selected");
});
$("#gvDisplayAvailItems tr").dblclick(function () {
AddDisplayParam($(this));
});
When I both double click and mass select rows on gvDisplayAvailItems, the rows are moved to gvDisplaySelectedItems correctly. However, nothing is triggered for the functions of gvDisplaySelectedItems for rows that were added via AddDisplayParams. Those added by AddDisplayParam can be highligted, but when double clicked only append another textbox to the row in gvDisplaySelectedItems.
So it seems that .clone and .cloneNode are doing something very different here despite having basically the same function. Could someone please explain why one partially works, while the other does not? And also, why my functions for the second grid are not triggered upon single and double click?
I'd suggest to try delegated event handlers.
E.g.
$("#gvDisplaySelectedItems").on("click", "tr", function () {
$(this).toggleClass("selected");
});
instead of
$("#gvDisplaySelectedItems tr").click(function () {
$(this).toggleClass("selected");
});
and so on for other event handlers.
More info
Regarding other improvements - you don't have to clone()/append()/remove() to move an element. Just doing append() to a new parent will effectively move it since an element can have only one parent each moment of time.
Example: JSFiddle

click event on a cell and not entire row - with FIDDLE

I am currently using this code for row click event in a bootstrap table
$('#myTable').bootstrapTable().on('click-row.bs.table', function (e, row, $element)
{
//....my operation
}
The problem is this triggers for the entire row and I want to be able to trigger it for a single cell.
Note I am using the arguments, row and $element
Here is the FIDDLE
$element is the entire row, you cannot know what cell have been clicked by this way,
bootstrap table do not have cell click event, so you need manually add click event on last cell and fill your needed vars yourself
$('#table').bootstrapTable({
data: data
}).on('click','td:last-child',function(){
var $t = $(this), $row = $t.parent(), i = $row.index(), row = data[i];
var $firstTd = $row.children().eq(0);
if($firstTd.data("haveTable") !== true){
$firstTd.data("haveTable",true);
$firstTd.append('<table class="newTable"><tr><td>NEW TABLE</td></tr></table>');
} else {
$firstTd.data("haveTable",false);
$firstTd.children("table").remove();
}
});
https://jsfiddle.net/e3nk137y/1663/
try
$('#myTable').bootstrapTable().on('click-row.bs.table td', function (e, row, $element)
{
//....my operation
}
Based on my guess, when you click on that cell, you probably want only the triggers for that particular cell to execute and not for the whole table.
This can be achieved by stopping the propagation of event from the table cell to the table row.
$('#myTable').bootstrapTable().on('click-row.bs.table', function (e, row, $element){
//stop the propagation for target cell
if($(event.target).hasClass('myClass')) e.stopPropagation();
//the code for handler
...
...
}
There are many ways stopPropagation can be utilized to do this thing. This was just one of those.
Since I dont know how your other triggers are set, I can't write code that works with those with assumptions.
Try this:
$('#myTable tr td:last-child').on('click', function() {
if( $('.newTable', $(this)).length ) {
$('.newTable', $(this)).remove();
} else {
$(this).append( '<table class="newTable"><tr><td>NEW TABLE</td></tr></table>' );
}
});

jQuery Traversing Dynamically generated DOM (next(), prev())

I have an HTML table and jQuery handlers to move rows up and down, using .next() and .prev(), but I also want to add new rows and after adding new row and trying to move old rows up or down they move more positions than expected. Here is an example on jsfiddle http://jsfiddle.net/3CQYN/
$(function() {
initControls();
$('.new').click(function() {
$('<tr><td>TEST</td><td>Up Down</td></tr>').appendTo($('table tbody'));
initControls();
});
});
function initControls()
{
$('.down').click(function() {
var parentRow = $(this).closest('tr');
parentRow.insertAfter(parentRow.next());
});
$('.up').click(function() {
var parentRow = $(this).closest('tr');
parentRow.insertBefore(parentRow.prev());
});
}
Try to move rows up and down, then add few new rows and move the OLD rows up and down again and you'll see the problem.
Every time you add a new row, you rebind the handlers, ending up with multiple handlers bound to individual up and down links. Instead, use event delegation (only executed once, on DOM ready):
$(document).on('click', '.down', function() {
// ...
});
$(document).on('click', '.up', function() {
// ...
});
http://jsfiddle.net/Gt4Zq/
Note that if you can find a container to bind to that is closer to the elements than document, that would be preferable.

Categories