I have a table with a default row and I am adding new rows dynamically with a button click, incrementing the ID of the tr and the innerText of the first td with a counter. I am trying to rearrange the ID's after deleting a row. Suppose I have 5 rows and I delete row nr 3, the 4th row should have the ID 3, and the 5th should have ID 4 etc. And also whena adding new rows it should rearrange the row ID's.
Here what I have so far. I have been trying but with no success or I dont get the desired results. Could anyone help me in the right direction?
<table class="table text-center table-borderless" id="rfqTable" style="font-size: 12px;">
<thead>
<tr>
<th>Item</th>
<th>Descr</th>
<th>Quantity</th>
<th>One Time</th>
<th>Supplier</th>
</tr>
</thead>
<tbody>
<tr id="1" class="tableRow">
<td class="item">1</td>
<td><textarea name="item[1]" rows="3" cols="90" maxlength="500"></textarea></td>
<td><input type="number" name="amount[1]"/></td>
<td><input type="checkbox" name="oneTime[1]" value="1"></td>
<td><input type="checkbox" name="supplier[1]" value="1"></td>
</tr>
</tbody>
</table>
Adding row:
var counter = 1;
var limit = 5;
document.getElementById("newItemBoxButton").addEventListener("click", function(){
if (counter == limit)
{
alert("Max row is 5!");
}
else
{
counter ++;
var table = document.getElementById("rfqTable");
var row = table.insertRow(-1);
row.setAttribute('id', counter );
var cell0 = row.insertCell(0);
cell0.innerHTML = counter;
cell0.setAttribute('id', 'item');
var cell1 = row.insertCell(1);
cell1.innerHTML = '<textarea name="item[' + counter + ']" rows="3" cols="90" maxlength="500"></textarea>';
var cell2 = row.insertCell(2);
cell2.innerHTML = '<input type="number" name="amount[' + counter + ']" style="width: 50px;"/>';
var cell3 = row.insertCell(3);
cell3.innerHTML = '<input type="checkbox" name="oneTime[' + counter + ']" value="1">';
var cell4 = row.insertCell(4);
cell4.innerHTML = '<input type="checkbox" name="supplier[' + counter + ']" value="1">';
var cell5 = row.insertCell(5);
cell5.innerHTML = '<span class="glyphicon glyphicon-remove"></span>';
}
});
Deleting row:
function deleteRow(rowid)
{
var row = document.getElementById(rowid);
var table = row.parentNode;
while (table && table.tagName != 'TABLE')
{
table = table.parentNode;
if (!table)
{
return;
}
table.deleteRow(row.rowIndex);
counter--;
}
var table = document.getElementById('rfqTable');
var trRows = table.getElementsByTagName('tr');
var tdRows = table.getElementsByTagName('td');
for (var i = 0; i < trRows.length; i++)
{
trRows[i].id = counter;
}
for (var i = 0; i < tdRows.length; i++)
{
document.getElementById("item").innerText = counter;
}
}
After deleting a row, all the row id's turn into the same id, and the td item doesnt change at all.
In deleteRow function, why you have added this -
for (var i = 0; i < trRows.length; i++) {
trRows[i].id = counter;
}
You are assigning same value to all rows since your counter variable is not changing. It should be like this -
trRows[i].id = i + 1; // added + 1 since you want to start from 1 not 0
ok, I got a fix. I targeted the first column of every row and changed that value. For loop has to start at 1, else it will also target the first th. So now the IDs will be rearranged after deleting a row and the value will always start at 1.
var table = document.getElementById('rfqTable');
for (var i = 1; i < table.rows.length; i++)
{
var firstCol = table.rows[i].cells[0];
firstCol.innerText = i;
}
Related
I am trying to write a JavaScript code to add multiple rows according to the number submited in an input text box. I am trying to do that by using a FOR loop but for some reason it does not work. Can you explain to me why it does not insert as many rows as the value from input text box??? Here is my code:
<!DOCTYPE html>
<html>
<head>
<br><meta charset=utf-8 />
<title>Insert rows in a Table</title>
</head>
<body>
<table id="table" border="1">
<tr>
<td>Row1 cell1</td>
<td>Row1 cell2</td>
</tr>
<tr>
<td>Row2 cell1</td>
<td>Row2 cell2</td>
</tr>
</table><br>
<form>
Type in a number:<input id="input" type="text" value=""}>
<input type="button" onclick="insert_Row()" value="add row(s)">
</form><br/>
<p id="p"></p>
<script>
var tableId = document.getElementById("table");
function insert_Row(){
var input = document.getElementById("input").value;
var number = Number(input);
for(i=0;i<number;i++){
var ii = i+1;
var newTR = table.insertRow(i);
var newTD1 = newTR.insertCell(i);
var newTD2 = newTR.insertCell(ii);
newTD1.innerHTML = "Row " + i + " Cell "+ i;
newTD2.innerHTML = "Row " + i + " Cell "+ ii;
};
};
</script>
</body>
</html>
The problem is irrespective of the row number, cells should start from 0,1,2 and so on which is not happening in your code. For the 0th iteration your code works fine, but later on, the cells do not start from 0. Hence the problem
Fix: Since you plan to have only 2 cells for each row, do it like this:
var tableId = document.getElementById("table");
function insert_Row() {
var input = document.getElementById("input").value;
var number = Number(input);
for (i = 0; i < number; i++) {
var j = 0; // First Cell
var k = 1; // Second Cell
var newTR = table.insertRow(i);
var newTD1 = newTR.insertCell(j);
newTD1.innerHTML = "Row " + i + " Cell " + j;
var newTD2 = newTR.insertCell(k);
newTD2.innerHTML = "Row " + i + " Cell " + k;
};
};
<table id="table" border="1">
</table>
<br>
<form>
Type in a number:
<input id="input" type="text" value=""/>
<input type="button" onclick="insert_Row()" value="add row(s)">
</form>
<br/>
<p id="p"></p>
The issue is with your document.getElementById declarations.
Also, it sounds like you want to insert the rows at the end of your table. In which case, your code will look like this.
var table = document.getElementById("table");
var numRows = document.querySelectorAll("tr").length;
function insert_Row(){
var input = document.getElementById("myInput").value;
var number = Number(input);
for (var i = numRows; i < number; i++) {
var ii = 0;
var ij = 1;
var newTR = table.insertRow(i);
var newTD1 = newTR.insertCell(ii);
var newTD2 = newTR.insertCell(ij);
newTD1.innerHTML = "Row " + (i + 1) + " Cell "+ (ii +1);
newTD2.innerHTML = "Row " + (i + 1) + " Cell "+ (ij + 1);
};
};
To use document.getElementById, you need to add an id attribute to your input tag like so.
<input id="myInput" type="button" onclick="insert_Row()" value="add row(s)">
Here is the updated fiddle
http://jsfiddle.net/vgwk00zm/2/
I'm trying to figure out how to use javascript to add rows to a table dynamically. I tested without the table and can get the data but am stumped on populating the table.
I have a function call on a button that is supposed to populate the table. below is my code so far:
<table id="tblData" class="pure-table">
<thead>
<tr>
<th>Staff</th>
<th>Orders</th>
</tr>
</thead>
<tbody>
<!--<tr class="pure-table-odd">
<td>Jim</td>
<td>2</td>
</tr>-->
</tbody>
</table>
function getData()
{
var soData = JSON.parse(staffOrders);
var i = 0;
var c = getRowCount();
//build table
var table = document.getElementById("tblData");
while (i <= c) {
//alert(soData[i].staffName + " had " + soData[i].orders + " orders.");
//"<td>" + soData[i].staffName + "</td>"
//"<td>" + soData[i].orders + "</td>"
i++;
}
}
You need to use the DOM API for the HTML table element. It's documented at
http://www.w3schools.com/jsref/dom_obj_table.asp
Here's an example taken from http://www.w3schools.com/jsref/met_table_insertrow.asp :
// Find a <table> element with id="myTable":
var table = document.getElementById("myTable");
// Create an empty <tr> element and add it to the 1st position of the table:
var row = table.insertRow(0);
// Insert new cells (<td> elements) at the 1st and 2nd position of the "new" <tr> element:
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
// Add some text to the new cells:
cell1.innerHTML = "NEW CELL1";
cell2.innerHTML = "NEW CELL2";
function getData() {
var responseData = [{
"staffName": "Wilkerson Bowman",
"orders": 26
}, {
"staffName": "Finley Nunez",
"orders": 26
}, {
"staffName": "Katie Estrada",
"orders": 7
}];
var thead = document.querySelector('#tblData thead');
responseData.forEach(function(data) {
var row = document.createElement('tr');
row.innerHTML = '<td>' + data.staffName + '</td><td>' + data.orders + '</td>';
thead.appendChild(row);
});
}
getData();
<table id="tblData" class="pure-table">
<thead>
<tr>
<th>Staff</th>
<th>Orders</th>
</tr>
</thead>
<tbody></tbody>
</table>
try this code
window.onload = function(){
function getData() {
var soData = [{orders : 'order1', staffName : 'staffName1'}, {orders : 'order2', staffName : 'staffName2'}]
var i = 0;
var c = 2;
//build table
var table_body = document.getElementById("tblData").getElementsByTagName('tbody')[0];
while (i <= c) {
var tr = document.createElement('tr');
tr.className = "pure-table-odd"; // add class in tr
var td1 = document.createElement('td');
td1.innerHTML = soData[i].orders;
var td2 = document.createElement('td');
td2.innerHTML = soData[i].staffName;
tr.appendChild(td1);
tr.appendChild(td2);
table_body.appendChild(tr);
i++;
}
};
getData();
}
<table id="tblData" class="pure-table">
<thead>
<tr>
<th>Staff</th>
<th>Orders</th>
</tr>
</thead>
<tbody>
<!--<tr class="pure-table-odd">
<td>Jim</td>
<td>2</td>
</tr>-->
</tbody>
</table>
At the moment only a cell is added to theclicked link's row and the bottom columns are not shown.
i would like the js code below to work such that if i click onany link say link 2 none of the top cells in the column are displayed apart from starting with the one inline with this link 2 and those below in the newly created column.
<table id="datble" class="form" border="1">
<tbody>
<tr>
<td>Add 1</td>
<td>
<label>Name</label>
<input type="text" required="required" name="BX_NAME[]" />
</td>
</tr>
<tr>
<td>Add 2</td>
<td>
<label>Name</label>
<input type="text" required="required" name="BX_NAME[]" />
</td>
</tr>
<tr>
<td>Add 3</td>
<td>
<label>Name</label>
<input type="text" required="required" name="BX_NAME[]" />
</td>
</tr>
</tbody>
</table>
<script type="text/javascript">
function addColumn(element) {
var tr = element.parentElement.parentElement;
var td = document.createElement("td");
td.innerHTML = '<label>Name</label>';
td.innerHTML += '<input type="text" required="required" name="BX_NAME[]" />';
tr.appendChild(td);
}
</script>
I have been trying out this code:
function appendColumn() {
var tbl = document.getElementById('my_table');
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for (var i = 0; i < tbl.rows.length; i++) {
var newcell = tbl.rows[i].insertCell(tbl.rows[i].cells.length);
for (var j = 0; j < colCount; j++) {
newcell.innerHTML = table.rows[0].cells[i].innerHTML;
}
}
}
but it doesn't do it.
jquery is also welcome
jsFiddle
If I correctly understood you need something like this:
function addColumn(element) {
var tr = element.parentElement.parentElement;
var trs = tr.parentElement.querySelectorAll( "tr" );
var trN = nInArray( trs, tr );
var tds = trs[ trs.length - 1 ].querySelectorAll( "td" );
var tdNextN = parseInt( tds[ tds.length - 1 ].querySelector( "input" ).name.match( /BX(\d+)_NAME\[\]/ )[ 1 ] );
if ( trN == 0 ) {
tdNextN++;
}
for ( var i = 0; i < trs.length; i++ ) {
var td = document.createElement( "td" );
if ( i >= trN ) {
td.innerHTML = "<label>Name" + tdNextN + "</label>";
td.innerHTML += "<input type=\"text\" required=\"required\" name=\"BX" + tdNextN + "_NAME[]\" />";
}
trs[ i ].appendChild( td );
}
}
function nInArray( array, object ) {
for ( var i = 0; i < array.length; i++ ) {
if ( array[ i ] === object ) {
return i;
}
}
return -1;
}
And that's what I think is required:
function addColumn(element) {
var tr = $(element).closest("tr")[0];
var allTrs = $(tr).closest("table").find("tr");
var found = false;
allTrs.each(function(index, item) {
if (item == tr) {
found = true;
}
var td = document.createElement("td");
if (found) {
td.innerHTML = '<label>Name</label>';
td.innerHTML += '<input type="text" required="required" name="BX_NAME[]" />';
}
item.appendChild(td);
});
}
Fiddle with this
Take a look of jquery
$('#datble').find('tbody').append('<tr><td>TD 1</td><td>TD 2</td></tr>');
//or you can prepend
$('#datble').find('tbody').prepend('<tr><td>TD 1</td><td>TD 2</td></tr>');
You can also try this throught jquery:
var html = "";
after
html += '<tr><td>TD</td></tr>';
or
html += '<tr>';
html += '<td>';
html += 'TD';
html += '</td>';
html += '</tr>';
and after all do this
$('#' + table_id ).append(html);
I have some code that is printing out a customers order on an order confirmation screen. It is doing this using Javascript to populate a table with the information. Ideally I would like to do this in JQuery
This is my HTML
<!-- Order Confirmation Form -->
<form action="<?the_permalink()?>" method="post">
<div id="summary">
<table id="ordertable">
<tr><th>Product</th>
<th>Quantity</th>
<th>Bulk</th>
<th>Options</th>
</tr>
</table>
<!-- Comments Box -->
Comments<br/>
<textarea name="comments"></textarea><br/>
<input name="product_list" id="products_field" type="hidden" value="<?= isset($_POST['product_list'])?$_POST['product_list']:'' ?>">
Next Day Delivery <input type="checkbox" name="next-day-delivery" value="yes" />
<input type="submit" value="Confirm Order" class="confirmBtn"/>
</div>
</form>
This is my JS
//Reference to the order table
var ordertable = document.getElementById("ordertable");
//Loop through the Array and display in the table
for(var i = 0; i < productArray.length; i ++){
//This is the data to display
console.log("Order Item " + i);
console.log("StockCode: " + productArray[i].stockCode);
console.log("Quantity: " + productArray[i].quantity);
console.log("Bulk: " + productArray[i].bulk);
var row = ordertable.insertRow(i + 1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
cell1.innerHTML = productArray[i].stockCode;
cell2.innerHTML = productArray[i].quantity;
cell3.innerHTML = productArray[i].bulk;
cell4.innerHTML = "<input type='button' value='-' class='removeBtn'/><input type='button' value='+' class='addBtn'/><input type='button' value='Delete' class='deleteBtn'/>"
}
This is an image of my page, I can't seem to figure out how I could add a select box to the cells below bulk (outlined in red). The idea being if bulk == true display a select box else don't show anything. (Some products can be ordered in bulk.)
Does anyone have any suggestions as to how I might go about achieving this?
Maybe simply something like
if(productArray[i].bulk)
cell3.innerHTML = "<select><option>1</option>..</select>";
Try like this
cell3.innerHTML = (productArray[i].bulk)?'<select><option value="...">...</option></select>':'';
Try this,
var select = '<select><option value="1">1</option><option value="2">2</option></select>';
cell3.innerHTML = productArray[i].bulk?select: '';
or just
cell3.innerHTML = productArray[i].bulk? '<select><option value="1">1</option><option value="2">2</option></select>' : '
for(var i = 0; i < productArray.length; i ++){
//This is the data to display
console.log("Order Item " + i);
console.log("StockCode: " + productArray[i].stockCode);
console.log("Quantity: " + productArray[i].quantity);
console.log("Bulk: " + productArray[i].bulk);
var row = ordertable.insertRow(i + 1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
var cell4 = row.insertCell(3);
cell1.innerHTML = productArray[i].stockCode;
cell2.innerHTML = productArray[i].quantity;
if(productArray[i].bulk) // true means select
cell3.innerHTML = "<select><option>1</option>..</select>"
else
cell3.innerHTML = '';
ell4.innerHTML = "<input type='button' value='-' class='removeBtn'/><input type='button' value='+' class='addBtn'/><input type='button' value='Delete' class='deleteBtn'/>"
}
So I have this table, and when I click on a td I would like to know where is that(which row and cell) without any attributes on the elements.
<table>
<tbody>
<tr>
<td>1</td>
<td>2</td> // If I click on this I would like to know tr:1 & td:2
<td>3</td>
</tr>
<tr>
<td>4</td>
<td>5</td>
<td>6</td>
</tr>
<tr>
<td>7</td>
<td>8</td>
<td>9</td>
</tr>
</tbody>
</table>
Javascript:
// Track onclicks on all td elements
var table = document.getElementsByTagName("table")[0];
var cells = table.getElementsByTagName("td"); //
for(var i = 1; i < cells.length; i++){
// Cell Object
var cell = cells[i];
// Track with onclick
cell.onclick = function(){
// Track my location;
// example: I'm in table row 1 and I'm the 2th cell of this row
}
}
In the handler, this is the table cell, so for the cell index do this:
var cellIndex = this.cellIndex + 1; // the + 1 is to give a 1 based index
and for the row index, do this:
var rowIndex = this.parentNode.rowIndex + 1;
Example: http://jsfiddle.net/fwZTc/1/
This script block will provide you the information you desire, by adding the information as properties to the cell and then accessing them in the onclick function:
// Track onclicks on all td elements
var table = document.getElementsByTagName("table")[0];
// Get all the rows in the table
var rows = table.getElementsByTagName("tr");
for (var i = 0; i < rows.length; i++) {
//Get the cells in the given row
var cells = rows[i].getElementsByTagName("td");
for (var j = 0; j < cells.length; j++) {
// Cell Object
var cell = cells[j];
cell.rowIndex = i;
cell.positionIndex = j;
cell.totalCells = cells.length;
cell.totalRows = rows.length;
// Track with onclick
console.log(cell);
cell.onclick = function () {
alert("I am in row " + this.rowIndex + " (out of " + this.totalRows + " rows) and I am position " + this.positionIndex + " (out of " + this.totalCells + " cells)");
};
}
}
Well, When you have rowspan/colspan you can have a lot more fun, however, if the grid is regular, you can just determine your position from the index by doing:
row = Math.floor(i / rows);
column = i % columns;
Using "this" on cells table
function myFunction(x) {
var tr = x.parentNode.rowIndex;
var td = x.cellIndex;
document.getElementById("tr").innerHTML = "Row index is: " + tr;
document.getElementById("td").innerHTML = "Column index is: " + td;
}
tr, th, td {
padding: 0.6rem;
border: 1px solid black
}
table:hover {
cursor: pointer;
}
<table>
<tbody>
<tr>
<td onclick="myFunction(this)">1</td>
<td onclick="myFunction(this)">2</td>
<td onclick="myFunction(this)">3</td>
</tr>
<tr>
<td onclick="myFunction(this)">4</td>
<td onclick="myFunction(this)">5</td>
<td onclick="myFunction(this)">6</td>
</tr>
<tr>
<td onclick="myFunction(this)">7</td>
<td onclick="myFunction(this)">8</td>
<td onclick="myFunction(this)">9</td>
</tr>
</tbody>
</table>
<p id="tr"></p>
<p id="td"></p>