HTML how to move through columns - javascript

I have the following code:
$(document).ready(function() {
var id = 'cbx';
var idPrefix = 'Arrow';
var html = '<img .../>';
// query parent row
var rowq = $('#' + id);
if (rowq.length < 1) {
rowq = $('.' + id);
VersionHeader = true;
}
if (rowq[0]) {
rowq.addClass('ArrowHeader');
// set to 0 for header
var index = 0;
var row = rowq.parents('.g')[0].insertRow(index);
// assign id for new row
row.id = idPrefix + id;
// assign classes for style and tree
row.className = 'srcrow' + id;
// insert new cell
var cell = row.insertCell(0);
// assign html result
cell.innerHTML = html;
// set colspan
cell.colSpan = 1;
Now my problem is it adds the cell but it adds it under the first column. Is there a way to move through the columns? Granted I'm not an html expert at all. Just a beginner trying to get some stuff to work and would appreciate some help since I'm totally lost. I didn't include the html just ... through it.
Thanks

I'm not sure I'm understanding your question entirely correctly (I gather you are attempting to insert a cell into a new row, and you want to select into which column it is inserted?). Assuming that's what you meant:
row.insertCell(0)
This is your problem. The insertCell method takes as an argument the index of the column into which the cell should be inserted. Index 0 is the first column, index 1 is the second column, and so on. So try replacing the 0 with the appropriate index.

Related

set id using setAttribute to td of last row of element

I am generating a table row which has two columns dynamically in html containing values from the database.
I want every td of the first column to have an unique id which i have done but i cant set the id to the td of last row in the table.
Here's the code to set id
<script>
var i=0;
var id=1;
while(i<100)
{
document.getElementsByTagName("td")[i].setAttribute("id", id);
i=i+2;
id=id+1;
}
</script>
Any help will be appreciated
but i cant set the id to the td of last row in the table.
You need to get to the last row in the table first.
var allRows = document.getElementsByTagName("tr");
var lastRow = allRows[allRows.length - 1];
now set Id to the first td of last row
lastRow.getElementsByTagName("td")[0].setAttribute("id" , allRows.length + 1 );
DOM Selectors are provided for a reason. :)
var tds = $('tr td:first-child');
var i=0;
$.each(tds, function(){
$(this).attr('id',i++);
});
OR
Using pure javascript
var tds = document.querySelectorAll('tr td:first-child');
var i = 0;
for(var td in tds){
tds[td].setAttribute('id',i++);
// or
//tds[td].id=(i++).toString();
};
You can use querySelectorAll to get all first td's withing given table using :first-child;
It will return NodeList which need to be convert into in an Array.
var arrTD = document.querySelectorAll("#list-notification tr td:first-child");
arrTD = Array.prototype.slice.call(arrTD);
var i =0;
arrTD.forEach(function(val,key){
val.setAttribute('id',i);
++i
})

Create Element with onclick

I have a table, and each row is added through JavaScript. I create these rows so that when they're clicked another cell will be created beneath them where I can display additional information. Now I want to be able to destroy the row I just created when the user clicks a button etc. So essentially, I need to be able to have the row I created have an onclick attribute, but it doesn't seem to work... I've tried everything I can think of so any help would be awesome!
var table = document.getElementById("main_table");
var row = table.insertRow(1);
row.id = count;
row.onclick = function ()
{
var id = this.id;
var target = document.getElementById(id);
var newElement = document.createElement('tr');
newElement.style.height = "500px";
newElement.id = id + "" + id;
//newElement.innerHTML = text;
target.parentNode.insertBefore(newElement, target.nextSibling );
//var newRow = document.createElement("tr");
//var list = document.getElementById(id);
//list.insertAfter(newRow,list);
var newRow = table.insertRow(newID);
}
I have tried to mimic your problem with below fiddle.
http://jsfiddle.net/kr7ttdhq/12/
newElement.onclick = createClickableCells;
del.onclick = delCell;
The above code shows the snippet from the fiddle
During the onclick event of the cell. New cells are created which in turn have the same onclick events as the first cell.
Moreover, a 'close' text cell is inserted by which you can delete the entire row.
Hope this helps

How to give a unique id for each cell when adding custom columns?

I wrote following code to add a custom column to my table. but i want to add a unique id to each cell in those columns. the format should be a(column no)(cell no>)
ex :- for the column no 4 :- a41, a42, a43, ........
So please can anyone tell me how to do that. Thank You!
$(document).ready(function ()
{
var myform = $('#myform'),
iter = 4;
$('#btnAddCol').click(function () {
myform.find('tr').each(function(){
var trow = $(this);
var colName = $("#txtText").val();
if (colName!="")
{
if(trow.index() === 0){
//trow.append('<td>'+iter+'</td>');
$(this).find('td').eq(5).after('<td>'+colName+iter+'</td>');
}else{
//trow.append('<td><input type="text" name="al'+iter+'"/></td>');
$(this).find('td').eq(5).after('<td><input type="text" id="a'+iter+'" name="a'+iter+'"/></td>');
}
}
});
iter += 1;
});
});
You seem to have code that's modifying the contents of the table (adding cells), which argues fairly strongly against adding an id to every cell, or at least one based on its row/column position, as you have to change them when you add cells to the table.
But if you really want to do that, after your modifications, run a nested loop and assign the ids using the indexes passed into each, overwriting any previous id they may have had:
myform.find("tr").each(function(row) {
$(this).find("td").each(function(col) {
this.id = "a" + row + col;
});
});
(Note that this assumes no nested tables.)
try this
if(trow.index() === 0){
//trow.append('<td>'+iter+'</td>');
$(this).find('td').eq(5).after('<td id="a'+column_no+cell_no+'">'+colName+iter+'</td>');
}else{
//trow.append('<td><input type="text" name="al'+iter+'"/></td>');
$(this).find('td').eq(5).after('<td id="a'+column_no+cell_no+'"><input type="text" id="a'+iter+'" name="a'+iter+'"/></td>');
}
you just have to define and iterate the column_no and cell_no variable
When all other cells are numbered consistently (for example using a data-attribute with value rXcX), you could use something like:
function addColumn(){
$('table tr').each(
function(i, row) {
var nwcell = $('<td>'), previdx;
$(row).append(nwcell);
previdx = nwcell.prev('td').attr('data-cellindex');
nwcell.attr('data-cellindex',
previdx.substr(0,previdx.indexOf('c')+1)
+ (+previdx.substr(-previdx.indexOf('c'))+1));
});
}
Worked out in this jsFiddle

Creating Table from Google Spreadsheets: How to Manipulate Data?

Currently, I'm working on a project to pull data from a Google Form/Spreadsheet and have it appear on a website using JQuery/DataTables. I had received help on getting the data to appear on the site, but I've hit a new issue.
Previous Question: Is it possible to create a public database (spreadsheet) search with Google Scripts?
On Google, I have a form which outputs eight columns:
Timestamp
Title
Author
Type
URL
Topic(s)
Country(s)
Tages
Of these, I don't need the timestamp to appear, and I would like the title to link to the URL if the URL exists. Since I'm not quite fluent with Javascript or DataTables, I made a second sheet which I tried to simplified it down to the following six:
Title (currently being formatted as an <a> tag using the URL)
Author
Type
Topic(s)
Country(s)
Tages
This almost works, except that the script I'm using to construct the table renders the Title field as it is in the cell with the being visible in the table. See the table under the title "Actual Output" for the current situation; the table under "Target Table Appearance" is what I'm aiming for.
Current Output: http://interculturalresources.weebly.com/webtest.html
Table Creation Script: http://www.weebly.com/uploads/1/7/5/3/17534471/tablescript.js
Thus, is there a way to have the be given as a link despite being put together in a Google Spreadsheet cell? Alternatively, is there a way to edit the current script to a) ignore the timestamp column and b) make the Title output a link to the URL from the URL column (with proper conditionals)?
EDIT: I'm focusing on the links now; I have a solution for the timestamp which involves copying the data to a new spreadsheet (since forms are strict with copy/pasting information). The current issue is getting each entry to have a link assuming the URL is in the first column, and the Title is in the second column. Please read Mogsdad's answer and my first comment for more information.
Solution: First, my thanks to Mogsdad for the "spark" of inspiration and insight which led me in the correct direction towards the solution. To explain the general idea, I wanted to not display one column (URL) from a Google Spreadsheet on the target website, yet use it's content to create a link in another (Title). Then, once the table was made, DataTables is used to format it. All cells in the table must contain something, so if the cell is to be blank, it must be filled with "None".
function cellEntries(json, dest, divId) {
var table = document.createElement('table');
table.setAttribute("id", divId + "table"); //Assign ID to <table> from the <div> name.
var thead = document.createElement('thead');
var tbody = document.createElement('tbody');
var thr;
var tr;
var entries = json.feed.entry;
var cols = json.feed.gs$colCount.$t; //The number of columns in the sheet.
var link; //Teporary holder for the URL of a row.
for (var i=0; i <cols; i++) { //For the first row of cells (column titles),
var entry = json.feed.entry[i];
if (entry.gs$cell.col == '1') { //For First Column / URL Column, (1)
if (thr != null) {
tbody.appendChild(thr);
}
thr = document.createElement('tr'); //Create <thr>/<tr> (???).
}
else { //For all other columns,
var th = document.createElement('th');
th.appendChild(document.createTextNode(entry.content.$t)); //Create title for each column.
thr.appendChild(th);
}
}
for (var i=cols; i < json.feed.entry.length; i++) { //For all remaining cells,
var entry = json.feed.entry[i];
if (entry.gs$cell.col == '1') { //For First Column / URL Column, (1)
if (tr != null) {
tbody.appendChild(tr);
}
tr = document.createElement('tr'); //Create <tr>.
hlink = entry.content.$t; //Put URL content into hlink.
}
else if (entry.gs$cell.col == '2') { //For Title Column,(2)
var td = document.createElement('td');
if (hlink != "None") { //If there is a link,
var alink = document.createElement('a'); //Make <a>
alink.appendChild(document.createTextNode(entry.content.$t)); //Put content in <a>
alink.setAttribute('href',hlink); //Assign URL to <a>.
td.appendChild(alink); //Put <a> in <td>.
}
else { //If there is no link,
td.appendChild(document.createTextNode(entry.content.$t)); //Put content in <td>.
}
tr.appendChild(td);
}
else { //For all other columns,
var td = document.createElement('td');
if (entry.content.$t != "None") { //If content is not "None",
td.appendChild(document.createTextNode(entry.content.$t)); //Output the content.
}
else { //Else,
td.appendChild(document.createTextNode("")); //Output a blank cell.
}
tr.appendChild(td);
}
}
$(thead).append(thr);
$(tbody).append(tr);
$(table).append(thead);
$(table).append(tbody);
$(dest).append(table);
$(dest + "table").dataTable();
};
function importGSS(json){
var divId = "targetdivid" //ID of the target <div>.
cellEntries(json, "#" + divId, divId);
};
Around this bit in tablescript.js:
var th = document.createElement('th');
th.appendChild(document.createTextNode(entry.content.$t));
>>>>
thr.appendChild(th)
You can add a hyperlink by doing this:
th.setAttribute('href',<link>);
...with <link> set to the hyperlink for the particular publication.
To make this work, you could rework your spreadsheet source to have the link in one column, and the Title in another. Then modify tablescript.js to combine the link and text, something like this:
var hlink = null; // Temporary storage for hyperlink
for (var i=0; i <cols; i++) {
var entry = json.feed.entry[i];
if (entry.gs$cell.col == '1') {
if (thr != null) {
tbody.appendChild(thr);
}
thr = document.createElement('tr');
}
// Element 0 assumed to have hyperlink
if (i == 0) {
hlink = entry.content.$t;
}
else {
var th = document.createElement('th');
// If we have an hlink, set the href attribute.
if (hlink !== null) {
th.setAttribute('href',hlink);
hlink = null;
}
th.appendChild(document.createTextNode(entry.content.$t));
thr.appendChild(th);
}
}

jQuery: Get next table cell vertically

How can I use jQuery to access the cell (td) immediately below a given cell in a traditional grid-layout html table (i.e., one in which all cells span exactly one row and column)?
I know that the following will set nextCell to the cell to the immediate right of the clicked cell because they are immediate siblings, but I am trying to retrieve the cell immediately below the clicked cell:
$('td').click(function () {
var nextCell = $(this).next('td');
});
Preferably I would like to do it without any use of classes or ids.
Try this:
$("td").click(function(){
// cache $(this);
var $this = $(this);
// First, get the index of the td.
var cellIndex = $this.index();
// next, get the cell in the next row that has
// the same index.
$this.closest('tr').next().children().eq(cellIndex).doSomething();
});
$('td').click(function () {
var index = $(this).prevAll().length
var cellBelow = $(this).parent().next('tr').children('td:nth-child(' + (index + 1) + ')')
});
index is the 0-based index of the cell in the current row (prevAll finds all the cells before this one).
Then in the next row, we find the nth-child td at index + 1 (nth-child starts at 1, hence the + 1).
How about:
$('td').click(function () {
var nextCell = $(this).parent().next().find("td:nth-child(whatever)");
});
If you want to do it without using selectors, you can do:
function getNextCellVertically(htmlCell){
//find position of this cell..
var $row = $(htmlCell).parent();
var cellIndex = $.inArray(htmlCell, $row[0].cells);
var table = $row.parent()[0];
var rowIndex = $.inArray($row[0], table.rows);
//get the next cell vertically..
return (rowIndex < table.rows.length-1) ?
table.rows[rowIndex+1].cells[cellIndex] : undefined;
}
$('td').click(function () {
var nextCell = getNextCellVertically(htmlCell);
//...
});
Not that efficiency is important here but it works out much faster to do it like this - in tests over 100,000 iterations it was 2-5 times faster than the selector based approaches.
Are there an equal number of cells in each table row? If so, you could get the "count" of the cell in question, then select the corresponding cell in the next('tr').

Categories

Resources