I'm tiring to use Handsontable jQuery module with jQuery UI drag&drop functionality, but without success. I've fount some code with insertAtCaret function, but I have troubles using it with Handsontable. I want to be able, to drag element from outside of Handsontable table, and drop it into cell. I know, that I have to update cell somehow... Please help...
CODE:
$.fn.insertAtCaret = function (myValue) {
return this.each(function(){
//IE support
if (document.selection) {
this.focus();
sel = document.selection.createRange();
sel.text = myValue;
this.focus();
}
//MOZILLA / NETSCAPE support
else if (this.selectionStart || this.selectionStart == '0') {
var startPos = this.selectionStart;
var endPos = this.selectionEnd;
var scrollTop = this.scrollTop;
this.value = this.value.substring(0, startPos)+ myValue+ this.value.substring(endPos,this.value.length);
this.focus();
this.selectionStart = startPos + myValue.length;
this.selectionEnd = startPos + myValue.length;
this.scrollTop = scrollTop;
} else {
this.value += myValue;
this.focus();
}
});
};
The insertAtCaret
code is not really what you need for this situation. You've already got a good handle on the required transaction - you need to use the ui.draggable
element in the drop
event to manually add some text to the correct cell. You just need a few final steps.
Now, one key piece of information is that Handsontable wants you to set cell data by coordinate, which means you need to know the column and row of the thing you want to set, not just have a javascript reference to the actual dom element. For that, we can use jQuery's index method.
setDataAtCell
method to change the data.$("#excel_table").droppable({
...
drop: function(event, ui) {
// Get a reference to the handsontable instance
var ht = $('#excel_table').handsontable('getInstance');
// Hide the helper, so that we can use .elementFromPoint
// to grab the item beneath the cursor by coordinate
ui.helper.hide();
var $destination = $(document.elementFromPoint(event.clientX, event.clientY));
// Grab the parent tr, then the parent tbody so that we
// can use their index to find the row and column of the
// destination object
var $tr = $destination.closest('tr');
var $tbody = $tr.closest('tbody');
var col = $tr.children().index($destination);
var row = $tbody.children().index($tr);
// Use the setDataAtCell method, which takes a row and
// col number, to adjust the data
ht.setDataAtCell(row, col, ui.draggable.text());
},
...
});