I am only getting back the entire row as a object, what I am trying to get is the second column's row data.
$('#table_id tbody').on('click', 'tr', function (e) {
var nTr = this;
var i = $.inArray(nTr, anOpen);
var aPos = oTable.fnGetPosition(this);
var aData = oTable.fnGetData(aPos[0]);
console.log(aData[0]);
if (i == -1) {
$(this).addClass('row_selected');
var nDetailsRow = oTable.fnOpen(nTr, fnFormatDetails(oTable, nTr, 1), 'details');
$('div.innerDetails', nDetailsRow).slideDown();
anOpen.push(nTr);
}
else {
$(this).removeClass('row_selected');
$('div.innerDetails', $(nTr).next()[0]).slideUp(function () {
oTable.fnClose(nTr);
anOpen.splice(i, 1);
});
}
});
$('#table_id tbody').on('click', 'tr', function (e) {
var secondColumn = this.cells[1]; // returns HTMLTableCellElement
Now you can work with secondColumn to get all the data you need, such as secondColumn.innerHTML. If you need to work with the cell in jQuery, just use
var secondColumn = $(this.cells[1]);
instead.
var table = document.getElementsByTagName("table")[0];
var rows = table.getElementsByTagName("tr");
for(var i = 0; i < rows.length; i++) {
var cell = rows[i].getElementsByTagName('td')[2];
var cellText = cell.childNodes[0];
if(cellText.data == '02/06/2010') {
// do something with cell
}
}
Try it here http://jsfiddle.net/ANsUq/
Related
Have small requirement, I have to select multiple cells in a table. Once we click on submit button we have to show the respective row data of the each cell in alert message.
I tried with below code, im getting cell data, but getting trouble to fetch row data of respective cell. Can any one help me pls,
Here is the sample code.
$(document).ready(function() {
var table = $('#example').DataTable();
$('#example tbody').on( 'click', 'td', function () {
$(this).toggleClass('selected');
// alert(table.cell( this ).data());
} );
$('#button').click(function() {
var rowdata = table.rows('.selected').data();
var cellData = table.cells('.selected').data();
//console.log(cellData);
var consoleMsg = '';
for (var i = 0; i < cellData.length; i++) {
consoleMsg += cellData[i]+'\n';
//consoleMsg += rowdata[i]+'\n';
}
alert(consoleMsg);
});
});
Fiddle
I found the solution you need. Try this:
$(function () {
var table = $('#example').DataTable();
var columnsNames = table.settings()[0].aoColumns.map(function (column) {
return column.sTitle;
});
$('#example tbody').on('click', 'td', function () {
$(this).toggleClass('selected');
});
$('#button').click(function () {
var selectedCells = table.cells('.selected');
var selectedCellsAddresses = selectedCells[0];
var selectedCellsData = selectedCells.data();
var selected = [];
var columnName;
selectedCellsAddresses.forEach(function (cell, index) {
if (!selected[cell.row]) {
selected[cell.row] = {};
}
columnName = columnsNames[selectedCellsAddresses[index].column];
selected[cell.row][columnName] = selectedCellsData[index]
});
console.log(selected);
alert(JSON.stringify(selected));
});
});
Fiddle
you can do whatever you want with that selected variable. :)
Hello I try to generate an HTML Table with two arrays. Where one array is for the Headers and the other one is for the rows. The arrays work like a blast but the generation of the HTML-Table wont work.....
Here is my little Function: (For the arrays and they work like a blast)
function loadDepartments() {
var query = "$select=DepartmentID,WEBName";
getListItems("example.at", "WEBepartments", query, function (results) {
results.forEach(function (result) {
departments.push({
name: result.WEBName,
id: result.DepartmentID
});
});
loadCountries();
},
function (error) {
console.log(error);
});
}
function loadCountries() {
var query = "$select=CountryID,WEBName,Acronym";
getListItems("https://intranet.windkraft.at/", "WEBCountries", query, function (results) {
results.forEach(function (result) {
countries.push({
name: result.WEBName,
id: result.CountryID,
acronym: result.Acronym
});
});
doNextSteps();
},
function (error) {
console.log(error);
});
}
And here my latest Try:
function doNextSteps() {
//Create a HTML Table element.
var table = document.createElement("TABLE");
table.border = "1";
//Get the count of columns and rows.
var columnCount = departments.length;
var rowCount = countries.length;
//Add the header row.
var row = table.insertRow(-1);
for (var i = 0; i < columnCount; i++) {
var headerCell = document.createElement("TH");
headerCell.innerHTML = columnCount[0];
row.appendChild(headerCell);
}
//Add the data rows.
for (var i = 1; i < countries.length; i++) {
row = table.insertRow(-1);
for (var j = 0; j < rowCount; j++) {
var cell = row.insertCell(-1);
cell.innerHTML = rowCount[0];
}
}
var dvTable = document.getElementById("dvTable");
dvTable.innerHTML = "";
dvTable.appendChild(table);
}
But wont work the only thing i get is nothing or undefined. And i have no clue why becouse its the first time i try to generate a HTML Table with javascript. So any help would be great.
Thx for your Time and Help.
I have a requirement to insert a new row after the selected row. The code which I have inserts a new row at the last which should only happen if user has not selected any row.
strGridId = test_ItemCollection_DefaultGridId(strGridId);
var grid = jQuery('#' + strGridId);
var columnModel = grid.jqGrid('getGridParam', 'colModel');
var currentItemCollection = test_ItemCollection_Get(strGridId);
var baseAddItem = function() {
var newTItem = proj.page.createTItem(currentItemCollection.strJSOName, strGridId, true);
newTItem.setUpdateStatus(UPDATESTATUS.ADD);
newTItem.set('transientItem', 1); // just created this item
// pre add item event
var evt = new TEvent(EVENT_PRE_ADD_ITEM, test_ItemCollection_Get(strGridId));
evt.strGridId = strGridId;
evt.newItem = newTItem;
if (!test_ItemCollection_fireEvent(evt)) {
return false;
}
currentItemCollection.items.push(newTItem);
var rowData = new Object();
for (var iGridLayout = 0; iGridLayout < columnModel.length; iGridLayout++) {
if (test_ItemCollection_IsNotJQGridColumn(columnModel[iGridLayout].name)) {
rowData[columnModel[iGridLayout].name] = test_ItemCollection_EncodeCellValue(strGridId, currentItemCollection.items.length-1, columnModel[iGridLayout], test_ItemCollection_GetItemDisplayValue(columnModel[iGridLayout], newTItem));
}
}
grid.jqGrid('addRowData', ''+ ( currentItemCollection.items.length-1), rowData ); // convert to string for adding 0 item
test_ItemCollection_selectRow(strGridId, '' + (currentItemCollection.items.length - 1) );
// post add item event
var evt2 = new TEvent(EVENT_POST_ADD_ITEM, test_ItemCollection_Get(strGridId));
evt2.strGridId = strGridId;
evt2.newItem = newTItem;
test_ItemCollection_fireEvent(evt2);
test_ItemCollection_AdjustGridHeight(strGridId);
return true;
};
How can I achieve this? Any help will be appreciated. Thanks
you can use .insertAfter() function of jQuery. For more details follow this link jQuery insertAfter
Assuming you have a table with id yourTable and every row that have been selected has a class of selectedRow
Add a button with id button and click it to add a new row:
$(document).on('click', '#button', function() {
var selRow = $('table#yourTable').find('tr.selectedRow');
var sel = selRow.length;
var newRow = '<tr><td>This is a new row</td></tr>';
if (sel > 0) {
selRow.after(newRow);
} else {
$('table#yourTable > tbody').append(newRow);
}
});
I have a problem in displaying the borders of my table correctly ,I work with jsPDF library ,this is the result that I get :
this is my code that selecet every row and display the data:
function tableToJson(table) {
var data = [];
// first row needs to be headers
var headers = [];
for (var i=0; i<table.rows[0].cells.length,i<5; i++) {
headers[i] = table.rows[0].cells[i].innerHTML.toLowerCase().replace(/ /gi,'');
}
data.push(headers);
// go through cells
for (var i=1; i<table.rows.length;i++) {
var tableRow = table.rows[i];
var rowData = {};
for (var j=0; j<tableRow.cells.length,j<5 ; j++) {
rowData[ headers[j] ] = tableRow.cells[j].innerHTML;
}
data.push(rowData);
}
return data;
}
function callme(){
var table = tableToJson($('#table').get(0));
var doc = new jsPDF('l','pt','letter',true);
$.each(table, function(i, row){
$.each(row, function(j,cell){
if(j=="email"){
doc.cell(1,10,190,20,cell,i);
}
else{
doc.cell(1,10,100,20,cell,i);
}
});
});
thanks for help
I am stuck. I am retrieving data from parse.com and trying to dynamically add them to their respective fields. What am I messing up on? I can console.log the data, so my get request is working. Thank you.
var parseData = function() {
var orderform = Parse.Object.extend("OrderForm");
var query = new Parse.Query(orderform);
query.find({
success: function (results) {
var tableRow = $('<tr />', {class: 'tableRows'});
var restaurantListP = [];
var tdId = [];
var tdEmail = [];
var tdMenuItems = [];
var tdNotes = [];
var tdPhoneNumber = [];
var table = $('#orderTable > tbody');
function newRow($table, cols){
$row = $('<tr/>');
for (var i = 0; i < cols.length; i++) {
$col = $('<td/>');
$col.append(cols[i]);
$row.append($col[i]);
}
table.append($row);
}
results.forEach(function (r, i) {
// tdId = $('<td />', { "id": r.id });
tdEmail = $('<td />', {email_address: r.attributes.email_address });
tdMenuItems = $('<td />', {menu_items: r.attributes.menu_items });
tdNotes = $('<td />', {notes: r.attributes.notes});
tdPhoneNumber = $('<td />', {phone_number: r.attributes.phone_number});
newRow(table,[tdId,tdEmail,tdMenuItems,tdNotes,tdPhoneNumber]);
// $('#orderTable > tbody').append(tableRow).append(restaurantListP[0]);
console.log(tdMenuItems);
console.log(tdEmail);
});
http://jsfiddle.net/DaveDH2/tb6d7w81/
There are two major errors:
id="orderTable" is set for <tbody>, not to <table>, so $('#orderTable > tbody') finds nothing. You should either move id="orderTable" to <table>, or rewrite selector to var table = $('#orderTable').
newRow function works incorrectly: it wraps already created <td> with another <td>, making <tr> html code incorrect. This function should be rewritten in something like this:
function newRow($table, cols)
{
var $row = $('<tr/>');
for (var i = 0; i < cols.length; i++)
{
$row.append(cols[i]);
}
$table.append($row);
}
Updated fiddle.