jQuery Add row to table with dynamic ids' - javascript

http://jsfiddle.net/waH5S/6/
function add_row_retail() {
$(document).ready(function () {
var table = document.getElementById("Retail");
var row = table.insertRow(-1);
var row_id = $('#Retail').val('tr[id]:last');
console.log(row_id);
var cell_init = row.insertCell(-1);
cell_init.innerHTML = "blank";
});
}
I am trying to get the id of the table row(<tr>) before the added row, and then add 1 to this, with proper parseint(...). Then doing the same with the cell (<td>) next, so that every cell has a unique id for each table. I can't seem to find the row's id.
HERE IS THE "CORRECT" CODE FOR MY QUESTION
function add_row_retail() {
var table = document.getElementById("Retail");
// Row id
var row_id = $('#Retail tr:last').attr('id');
var row = table.insertRow(-1);
var next_row_id = "tr_" + (1+parseInt(row_id.match(/\d+/)[0],10));
$(row).attr('id', next_row_id);
for (var i = 0; i < 8; i++) {
var cell_id = $('#Retail td:last').attr('id');
console.log(cell_id);
var next_cell_id = "td_" + (1+parseInt(cell_id.match(/\d+/)[0],10)); console.log(next_cell_id);
var cell = row.insertCell(-1);
$(cell).attr('id', next_cell_id);
$(cell).innerHTML = "blank";
}
}

Rather than $('#Retail').val('tr[id]:last'); I think you want:
var row_id = $('#Retail tr:last').attr('id')
This selector finds the last tr under the #Retail element, and returns its id attribute.
jQuery last selector: http://api.jquery.com/last-selector/
Next problem: IDs cannot start with numbers. Rename your IDs like "tr_1", "tr_2", etc.
Next problem: To extract the numbers from a string:
"tr_123".match(/\d+/)[0]; // returns 123.
Add 1 to it:
var next_id = "tr_" + (1+parseInt("tr_123".match(/\d+/)[0],10));
Then, set your new id.
var row = table.insertRow(-1);
...
$(row).attr('id', next_id);

Related

How to dynamically add <a> in a html table?

I have a table generated from an array. I'm looking to add a hyperlink to the entire first column of the <tbody> and only the first column.
I am able to add the <a> after the table is created, but then it doesn't actually contain the url within it, it simply appends to what already exists.
Specifically, how can I add a hyperlink to the first column of the
<tbody>?
Generally, as the table is being made, how can I specify different
things (anchors, classes, styles, etc.) for different columns?
http://jsfiddle.net/nateomardavis/n357gqo9/10/
$(function() {
google.script.run.withSuccessHandler(buildTable)
.table();
});
//TABLE MADE USING for
function buildTable(tableArray) {
var table = document.getElementById('table');
var tableBody = document.createElement('tbody');
var tbodyID = tableBody.setAttribute('id', 'tbody');
for (var i = 0; i < tableArray.length; ++i) {
var column = tableArray[i];
var colA = column[0];
var colB = column[1];
var colC = column[2];
var colD = column[3];
if (colA != "") {
var row = document.createElement('tr');
var getTbody = document.getElementById('tbody');
for (var j = 0; j < column.length; ++j) {
var cell = document.createElement('td');
cell.appendChild(document.createTextNode(column[j]));
row.appendChild(cell);
//NEXT TWO LINES DO NOT WORK
var firstCol = getTbody.rows[i].cells[0];
firstCol.setAttribute('class', 'TEST');
}
}
tableBody.appendChild(row);
}
table.appendChild(tableBody);
document.body.appendChild(table);
/* WORKS AFTER TABLE IS CREATED BUT CAN'T CAPUTRE INTERNAL LINK
var getTbody = document.getElementById('tbody');
for (var i = 0; i < getTbody.rows.length; i++) {
var firstCol = getTbody.rows[i].cells[0]; //first column
//firstCol.style.color = 'red';
//firstCol.setAttribute('class', 'TEST');
var link = document.createElement('a');
firstCol.appendChild(link);
}
*/
}

javascript multiple array into json

How to get each table row and its respective inputs (checkbox, text, select) into an array to store in localstorage? I've complete most of the code, the part I need to build is the ???? part. Thanks.
This is the javascript code:
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for(var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[0].cells[i].innerHTML;
}
}
$('#btnSave').on('click', function(e) {
e.preventDefault();
var id = $(this).attr("data-id");
var mykey = 'set'+id;
// here just to check whether 'set'+id exist or not, no validation performed
if(localStorage.getItem(mykey)==null){
console.log('key not found');
} else {
console.log('key found');
}
// Due to there will be one or more rows,
// need to loop the rows and get the inputs within
// and store them in localstorage
$('#dyn_table tr').each(function(){
var tr = $(this);
var checkbox = $(this).find('.big-checkbox').is(':checked');
var itemcode = $(this).find('.dyn_item_code :selected').val();
var amount = $(this).find('.dyn_amount').val();
var reference = $(this).find('.dyn_reference').val();
console.log(checkbox);
console.log(itemcode);
console.log(amount);
console.log(reference);
});
localStorage.setItem(mykey, ????);
});
This is the input button if you wonder how i dynamically generate the table row
<input type="button" value="Add row" onClick="addRow('dyn_table')" />
Create an array of objects.
var array = [];
$('#dyn_table tr').each(function(){
var tr = $(this);
var checkbox = $(this).find('.big-checkbox').is(':checked');
var itemcode = $(this).find('.dyn_item_code :selected').val();
var amount = $(this).find('.dyn_amount').val();
var reference = $(this).find('.dyn_reference').val();
array.push({
checkbox: checkbox,
itemcode: itemcode,
amount: amount,
reference: reference
});
console.log(checkbox);
console.log(itemcode);
console.log(amount);
console.log(reference);
});
localStorage.setItem(mykey, JSON.stringify(array));
I didn't know if I understood your problem but this is working ?
var my_table = [] // Create an array for the table
$('#dyn_table tr').each(function(){
var tr = $(this);
var checkbox = $(this).find('.big-checkbox').is(':checked');
var itemcode = $(this).find('.dyn_item_code :selected').val();
var amount = $(this).find('.dyn_amount').val();
var reference = $(this).find('.dyn_reference').val();
// For each row, create a item on the array, containing all important data for the row
my_table.push({checkbox, itemcode ,amount, reference})
});
console.log("My table :", my_table)
localStorage.setItem(mykey, JSON.stringify(my_table));
If you don't want to save each col like: {checkbox: true, itemcode: 'foo', ...} but have an ordered array instead, you can replace the new line by:
my_table.push([checkbox, itemcode ,amount, reference])

Generate Table with only one Column

Hello i try to generate a table with only one column. So my Links get displayed in only one column.
Here is my function:
function createTableForPdfFiles() {
//To Create The Table
var table = document.createElement("table");
table.setAttribute('id', 'pdfTable');
table.setAttribute('class', 'AANTable');
// insert Title Row
var TitleRow = table.insertRow();
var cell = TitleRow.insertCell();
cell.setAttribute('class', 'AANTitleRow');
cell.setAttribute('colSpan', pdfFiles.length + 1);
cell.appendChild(document.createTextNode("Datenblätter"));
//Insert Table Rows
var pdfRow = table.insertRow();
var cell = pdfRow.insertCell(); //Where the PDF´s are displayed
cell.setAttribute('class', 'AANPdfRow');
for (var i = 0; i < pdfFiles.length; i++) {
var cell = pdfRow.insertCell();
var link = document.createElement("a");
link.setAttribute("href", "www.test.at" + pdfFiles[i].Link);
var linktext = document.createTextNode(pdfFiles[i].Link);
link.appendChild(linktext);
cell.appendChild(link);
cell.setAttribute('class', 'AANPdfCell');
}
$("#divTable").append(table);
}
Right now it looks like:
But i want it to look like:
So how i can i make that possibe? I tried to add another Row to the table but the debugger says not supported...... Any help would be really great.
thanks for your Time.
You have to create anew row foer each pdf.
Hae to put this
var pdfRow = table.insertRow();
var cell = pdfRow.insertCell(); //Where the PDF´s are displayed
cell.setAttribute('class', 'AANPdfRow');
Inside the for
take a look at this -> fiddle

How to find out which row was clicked?

Hello i generate a Table with javascript and now i wont to find out which row and column the user has clicked?
Here are my function for the table:
function doNextSteps() {
removeAustriaFromCountries();
//insert table
var table = document.createElement("table");
table.setAttribute('id', 'matrixTable');
table.setAttribute('class', 'jbiTable');
// insert MATRIX row
var matrixRow = table.insertRow();
var cell = matrixRow.insertCell(); // left column for countries
cell.setAttribute('class', 'jbiMatrixCell');
cell.setAttribute('colSpan', departments.length + 1);
cell.appendChild(document.createTextNode("MATRIX"));
// insert departments row
var departmentsRow = table.insertRow();
var cell = departmentsRow.insertCell(); // left column for countries
cell.setAttribute('class', 'jbiBlankCell');
for (var i = 0; i < departments.length; i++) {
var cell = departmentsRow.insertCell();
cell.appendChild(document.createTextNode(departments[i].name));
cell.setAttribute('class', 'jbiDepartmentCell');
}
for (var i = 0; i < countries.length; i++) {
var countryRow = table.insertRow();
var cell = countryRow.insertCell(); // left country column
//cell.appendChild(document.createTextNode(countries[i].name));
var img = document.createElement('img');
img.src = "example.com + flags[i].name";
cell.appendChild(img);
cell.setAttribute('class', 'jbiCountryCell');
for (var j = 0; j < departments.length; j++) {
var cell = countryRow.insertCell();
var img = document.createElement('img');
img.src = "https://intranet.windkraft.at/OrganisationManual/Documents/Kreis.jpg";
img.onclick = function () {
window.location.href = "example.com" + pdfFiles[i].name;
};
cell.appendChild(img);
cell.setAttribute('class', 'jbiCircleCell');
}
}
$("#divTable").append(table);
}
The table gets generated and now i want to know in which header and in which column the user has clicked. With that information i want to make a new query to get files dynamically displayed in the Table. Any help would be great. And thanks for your Help.
To get the index of the row, you can use this code in your event listener function:
function onClick() {
var cell = this;
var row = cell.parentNode;
var cellIndex = Array.prototype.indexOf.call(row.children, cell);
var rowIndex = Array.prototype.indexOf.call(row.parentNode.children, row);
// do stuff with rowIndex, cellIndex
// rowIndex is the row number starting with row 0
// cellIndex is the column number starting with column 0
}
You can use parentNode.rowIndex & cellIndex to get the cell & rowIndex
document.getElementsByTagName('table')[0].addEventListener('click', function(e) {
console.log(e.target.parentNode.rowIndex,' ',e.target.cellIndex);
}, false);
Check this jsFiddle

Create a bookmarklet that can retrieve all max length of text box and then print the id and max length in a table

I want to create a bookmarklet by using javascript, which can retrieve max length of all text box in the page, and then print a table below the page with all id and max length indicated.
Here is my code, however it did not print anything.
javascript: (function() {
var body =document.getElementsByTagName('body')[0];
var tbl = document.createElement('table');
var tbdy = document.createElement('tbody');
var D = document,
i, f, j, e;
for (i = 0; f = D.forms[i]; ++i)
for (j = 0; e = f[j]; ++j)
if (e.type == "text") S(e);
function S(e) {
var l= document.getElementById(e.id);
var x = document.getElementById(e.maxlength);
var tr=document.createElement('tr');
var td1=document.createElement('td');
var td2=document.createElement('td');
td1.appendChild(document.createTextNode(l));
td2.appendChild(document.createTextNode(x));
tr.appendChild(td1);
tr.appendChild(td2);
tbdy.appendChild(tr);
}
tbl.appendChild(tbdy);
body.appendChild(tbl);
})
This can actually be done much simpler than you have it.
Working jsfiddle: https://jsfiddle.net/cecu3daf/
You want to grab all of the inputs and run a loop over them. From this you can dynamically create a table and append it to the end of the document.body
var inputs = document.getElementsByTagName("input"); //get all inputs
var appTable = document.createElement("table"); //create a table
var header = appTable.createTHead(); //create the thead for appending rows
for (var i=0; i<inputs.length; i++) { //run a loop over the input elements
var row = header.insertRow(0); //insert a row to the table
var cell = row.insertCell(0); //insert a cell into the row
cell.innerHTML = inputs[i].maxLength; //input data into the cell
var cell = row.insertCell(0);
cell.innerHTML = inputs[i].id;
}
document.body.appendChild(appTable); //append the table to the document
To make it a bookmark, simply place the javascript: before hand. There is no need to encase it in a function. You can if you'd like to.

Categories

Resources