Drag and Drop div into table and get the data value - javascript

I set the div data value in table cells, what I want is how to get the div data value, while drop.
In my code, I set the data in the table like this
<script type="text/javascript">
function createDynamicTable(tbody, rows, cols) {
if (tbody == null || tbody.length < 1) return;
for (var r = 1; r <= rows; r++) {
var trow = $("<tr>");
for (var c = 1; c <= cols; c++) {
var cellText = "Cell " + r + "." + c
$("<td>")
.addClass("tableCell")
.text(cellText)
.data("col", c)
.appendTo(trow);
}
trow.appendTo(tbody);
}
}
In my code, on clicking the cell of table, I get the row and column data div values
$(document).ready(function() {
createDynamicTable($("#tbl"), 10, 5);
$("#tbl td.tableCell")
.click(function() {
alert("Clicked Col=" + $(this).data("col"));
});
});
it is working perfectly
for full code view the site:
http://blogs.microsoft.co.il/blogs/linqed/archive/2009/03/04/generating-html-tables-with-jquery.aspx
I try like this but I cann't getting the table cell data value on stop event. How to get the setted data value in drag and drop.
$(".drag").draggable({
stop: function (ev, ui) {
var pos = $(ui.helper).offset();
var oldData = $("#tbl td.tableCell").data('col');
alert(oldData);
}
});
Help me to get the data value in drag and drop.
Thanks in advance.

Drag and Drop could be restructuring the DOM. Try Using jQuery.live instead of jQuery.click (if supported by your jQuery version) to bind the click event:
$("#tbl td.tableCell")
.live('click', function() {
alert("Clicked Col=" + $(this).data("col"));
});
Since .live() is deprecated you may also want to try the .on() method (if using jQuery 1.7.x).

Related

insertRow not working in for loop in JS

$(function(){
$('#sizePicker').submit(function makeGrid(evt) {
$('#pixel_canvas').empty();
evt.preventDefault();
var row = $('#input_height').val();
var cell = $('#input_width').val();
var table = $('#pixel_canvas');
for(r = 0; r <= row; r++){
var addRow = table.insertRow(r)
for(c = 0; c <= cell; c++){
addRow.insertCell(c);
}
}
});
});
This is my code to add rows and cells based on input, but for some reason when I use .insertRow and .insertCell there's no output, but when I use .append the function works perfectly. Anyone know why?
You are treating table like it's in the dom but it is a jQuery element so that wouldn't work.
Try this
table.get(0).insertRow(r)

jQuery filter for table

I have created a table but somehow now able to filter the row. Its giving me error as cannot read property split. Here is the link to my fiddle file. Any help would be great. Thanks in advance.
$("#crudtable_filter").keyup(function () {
//split the current value of searchInput
var data = this.value.split(" ");
//create a jquery object of the rows
var jo = $("#crudtable").find("tr");
if (this.value == "") {
jo.show();
return;
}
//hide all the rows
jo.hide();
//Recusively filter the jquery object to get results.
jo.filter(function (i, v) {
var $t = $(this);
for (var d = 0; d < data.length; ++d) {
if ($t.is(":contains('" + data[d] + "')")) {
return true;
}
}
return false;
})
//show the rows that match.
.show();
}).focus(function () {
this.value = "";
$(this).css({
"color": "black"
});
$(this).unbind('focus');
}).css({
"color": "#C0C0C0"
});
Working fiddle: http://jsfiddle.net/sofqjbrg/3/
Explanation:
In order to get the value of the element that rigger the event, you need to use $(event.target).val().
For the difference between $(event.target) and $(this), please refer to Difference between $(this) and event.target?
PS: Your focus event is registered to the wrong element.

How to make a button functional when loaded into a row from local storage in javascript

//loops through all rows and cells and saves them into local storage as objects
window.onbeforeunload = function() {
var rows = document.getElementById('firsttable').tBodies[0].rows;
for (var i = 0; i < rows.length; i += 1) {
localStorage.setItem(i, JSON.stringify({
Item: rows[i].cells[0].innerHTML,
filling1: rows[i].cells[1].innerHTML,
filling2: rows[i].cells[2].innerHTML,
filling3: rows[i].cells[3].innerHTML,
Stock: rows[i].cells[4].innerHTML,
min: rows[i].cells[5].innerHTML,
sold: rows[i].cells[6].innerHTML,
closeAcc: rows[i].cells[7].innerHTML,
sell: rows[i].cells[8].innerHTML,
dltButton: rows[i].cells[9].innerHTML
}));
};
};
//loads the objects into rows with the values in their cells
window.onload = function() {
var r = 0,
c = 0;
//load the actual data from localstorage into html rows
for (x in localStorage) {
var row = table.insertRow(r),
obj = JSON.parse(localStorage.getItem(x));
for (i in obj) {
var cell = row.insertCell(c);
cell.innerHTML = obj[i];
c += 1
}
r += 1;
c = 0;
}
};
//where the problem is
$(function() {
$('table td').click(function(e) {
if (e.target.id === "Sellbtn") {
var sell = prompt("Enter the amount");
for (var i = 0; i < table.length; i += 1) {};
this.parentNode.parentNode.cells[4].innerHTML = parseInt(this.parentNode.parentNode.cells[4].innerHTML) - sell; //not working and no when put inside the for loop it doesn't work idk why
} else if (e.target.id === "Deletebtn") {
return false;
} else {
var ask = prompt("Input");
$(this).html(ask);
}
});
});
So i insert a row and add the details to the cells and such then as explained in the snippet the first function saves available the rows and cells into a JSON stringified object in the localstorage when the user is closing the browser and then loads them up during onload the problem is with the buttons idk how to make them function after the onload(user closes and opens again). So imagine this you have your HTML table with several rows and their cells and each row has the two buttons(sell and delete) how do i make them function when the user opens up the application again? and btw the buttons are both dynamically added using createElement() when the row is originally added
Try delegating the click event you have on your table rows since they're being created after the DOM loads:
$('table').on("click", "td", function(e) {

Set a cell value and keep it editable in inline editing

I have to change a cell value by code and keep it editable. With this code, I can change the value of the other cell, but the cell 'paidHour' change to a non-editable state.
How to make it editable again?
editoptions: { dataEvents: [{ type: 'keyup', fn: function (e) {
var rowId = $(e.target).closest("tr.jqgrow").attr("id");
var total = parseInt(e.target.value, 10);
var paidWeek = parseInt($("#List").getCell(rowId, 'paidWeek'), 10);
var addHourBank = 0;
if (total >= paidWeek) {
addHourBank += (total - paidWeek);
total = paidWeek;
}
$("#List").setCell(rowId, 'paidHour', total);
I am not sure that I understand you correct. It's important to distinguish editing and editable cells/rows. The editable is the row or the cell which can be edited with respect of form editing, inline editing or cell editing. Probably the cell are editing currently and you want to change the value of the cell. In the case you can't use setCell method. Instead of that you have to get the <td> as DOM or as jQuery wrapper and then set value of the child <input> element of the cell.
For example you can use getColumnIndexByName function defined as following
var getColumnIndexByName = function (grid, columnName) {
var cm = grid.jqGrid('getGridParam', 'colModel'), l = cm.length, i;
for (i = 0; i < l; i++) {
if (cm[i].name === columnName) {
return i; // return the index
}
}
return -1;
}
It gets you the index of the column inside of the row. So you can split the line
var rowId = $(e.target).closest("tr.jqgrow").attr("id");
into
var $tr = $(e.target).closest("tr.jqgrow"), rowId = $tr.attr("id");
The $tr represents the jQuery wrapper of the DOM of <tr>. So to get the <td> cell for 'paidHour' you can use
var iCol = getColumnIndexByName ($(this), 'paidHour');
var $td = $tr.find(">td:nth-child(" + (iCol + 1) + ")");
and to change the value of the cell you can use
$td.find("input").val(total);

Traversing table and returning clicked element's placement

I have an onclick function attached to each <td> element. The function needs to know the placement in the table (row and column).
I found an attribute called rowIndex for <tr>s, but that would involve getting the parent element and still doesn't help with column number.
Here is my function so far (it's within a loop, so it's attaching to every td)
td.onclick = function(event) {
event = (event) ? event : window.event;
console.log('rowIndex, colIndex');
}
I could figure this out with jQuery, but I'm trying to do without.
My first thoughts were:
var rows = document.getElementsByTagName('tr');
var cells = document.getElementsByTagName('td');
var cellsPerRow = cells.length/rows.length;
var i = 0;
for (r=0;r<rows.length;r++){
for (c=0;c<cellsPerRow;c++){
cells[i].setAttribute('data-col',c + 1);
cells[i].setAttribute('data-row',r + 1);
cells[i].onclick = function(){
var row = this.getAttribute('data-row');
var col = this.getAttribute('data-col');
alert('Row: ' + row + '; col: ' + col);
};
i++;
}
}
JS Fiddle demo.
This was then refined to:
var cells = document.getElementsByTagName('td');
for (i=0;i<cells.length;i++){
cells[i].onclick = function(){
var row = this.parentNode.rowIndex + 1;
var col = this.cellIndex + 1;
alert('Row: ' + row + '; col: ' + col);
};
}
JS Fiddle demo.
element.cellIndex
will give you the column zero-indexed position.
Example
Is it possible in your situation to echo out the row and column into the td element's id in the server-side script? Such as ...id="' . $row . '_' . $col . '"...
Then it's just a case of parsing the values out from this.id.
Here you go: - http://jsfiddle.net/FloydPink/Lu8Yw/
var tds = document.getElementsByTagName('td');
for (var i = 0; i < tds.length; i++) {
var td = tds[i];
td.onclick = function(event) {
event = (event) ? event : window.event;
console.log('rowIndex: ' + this.parentNode.rowIndex + ', colIndex: ' + this.cellIndex);
}
}
First, creating click events for each td is not efficient. Recommend using event delegation. You can google it for the benefits of using Event delegation.
http://www.nczonline.net/blog/2009/06/30/event-delegation-in-javascript/
Basically, the more cells you have in the table, the more memory will be consumed. Instead of creating multiple cells, create one single event to delegate.
var table = document.getElementById('test-table');
table.onclick = function(e) {
var target = e.target,
parent;
if (target.tagName === 'TD') {
parent = target.parentNode;
console.log('rowIndex', parent.getAttribute('rowindex'), 'colIndex', target.getAttribute('colindex'));
}
}
Here is the example in jsfiddle http://jsfiddle.net/EWGzB/1/

Categories

Resources