Add rows and data - javascript

So currently I can add rows with this code:
function addRow(){
var tableRef = document.getElementById('myTable').getElementsByTagName('tbody')[0];
// Insert a row in the table at row index 0
var newRow = tableRef.insertRow(tableRef.rows.length);
// Insert a cell in the row at index 0
var newCell = newRow.insertCell(0);
// Append a text node to the cell
var newText = document.createTextNode('New row')
newCell.appendChild(newText);
}
Here is my table:
<table id="myTable" border="2px">
<tbody>
<td>
Module 1
</td>
<td>
Introduction
</td>
<td id="info">
</td></tr>
<tr>
<td>
<div id="button"> Add Another Row </div>
</td></tr>
</tbody>
</table>
Here is how I add data to the row:
function showChoices()
{
//retrieve data
var selLanguage = document.getElementById("productchoice3");
//set up output string
var result="<ul> \n";
//step through options
for (i = 0; i < selLanguage.length; i++)
{
//examine current option
currentOption = selLanguage[i];
//print it if it has been selected
if (currentOption.selected == true)
{
console.log(currentOption.label);
result += " <li>" + currentOption.label + "<br>" + currentOption.value + "<\/li> \n";
} // end if
} // end for loop
//finish off the list and print it out
result += "<\/ul> \n";
output = document.getElementById("info");
output.innerHTML = result;
document.getElementById('info').style.display='block';
}
What I want to do is have the "add another row" move down each time I click it, so I can add infinite rows, and have a way to add data to the newest row that was created.

You could easily add an id to the row, by doing:
var newRow = tableRef.insertRow(tableRef.rows.length);
newRow.id = "whateverYouWant";

Related

Find values in table cells with Javascript

I'm using a dynamic table in HTML, but I need to verify the values are not repeated. I'm trying to do it with the value inside the cell rather than the text. These are the values and what I have so far:
var tBody = $("#tablaAplicaciones > TBODY")[0];
//Add Row.
var row = tBody.insertRow(-1);
//Add Name cell.
var cell = $(row.insertCell(-1));
cell.html(nameCountry);
cell.val(idCountry);
//Add Country cell.
cell = $(row.insertCell(-1));
cell.html(nameCompany);
cell.val(idCompany);
if (($('#tablaApp tr > td:contains(' + countryName + ') + td:contains(' + companyName + ')').length) == 1) {
.
.
.
}
Welcome to Stack Overflow. Consider the following code.
$(function() {
var idCountry = "9";
var nameCountry = "United States";
var idCompany = "9";
var nameCompany = "Genentech";
var tBody = $("#tablaAplicaciones > tbody");
//Create Row
var row = $("<tr>");
//Add Country cell to Row
$("<td>", {
class: "name-country"
})
.data("id", idCountry)
.html(nameCompany)
.appendTo(row);
//Add Company cell to Row
$("<td>", {
class: "name-company"
})
.data("id", idCompany)
.html(nameCompany)
.appendTo(row);
// Assume vales are not in the table
var found = -1;
$("tr", tBody).each(function(i, el) {
// Test each row, if value is found set test to tue
if ($(".name-country", el).text().trim() == nameCountry) {
found = i;
}
if ($(".name-company", el).text().trim() == nameCompany) {
found = i;
}
});
if (found == -1) {
// If test is false, append the row to table
row.appendTo(tBody);
console.log("Row Added", row);
} else {
console.log("Values already in Table, row: " + found);
}
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table id="tablaAplicaciones">
<thead>
<tr>
<th>Country</th>
<th>Company</th>
</tr>
</thead>
<tbody>
<tr>
<td data-id="1" class="name-country">United States</td>
<td data-id="1" class="name-company">Apple Inc.</td>
</tbody>
</table>
Using .each(), you can iterate over each row and compare the values. A variable can be used as a flag to indicate if the needle was found in the haystack. If not found, you can append the row. Otherwise, do not add the row.
Hope that helps.

JavaScript output not iterating correctly

I am using javascript to clone a row then renaming the element id's and incrementing one of the values by 1. This is not the actual code I'm working on but a generic example that shows the problem.
It is appending everything to the top of my row instead of below it
It increments once or twice then stops
The output I'm getting is:
10022018
10032018
10032018
10032018
10032018
10012018
What I'm expecting is:
10012018
10022018
10042018
10052018
10062018
10072018
<table id = "myTable">
<tr id="myRow">
<td>First cell <input type="text" id = "input" value = "10012018"></td>
</tr>
</table><br>
<button onclick="myFunction()">Try it</button>
<script>
function myFunction() {
var i;
for(i=0; i<5;i++){
var row=document.getElementById("myRow");
var cln = row.cloneNode(true);
row.id = "rows" + i;
var inpa = document.getElementById("input");
inpa.id = "input" + i;
var a = parseFloat(document.getElementById("input0").value);
inpa.value = (a + 10000);
document.getElementById("myTable").appendChild(cln);
}
}
</script>
Edit
Robin Zigmond added that input0 was the culprit and not incrementing (corrected but I failed to explain).
var a = parseFloat(document.getElementById("input0").value); // Should be "input"
inpa.value = (a + (10000)); // Needs increment ...a + (10000 * i));
My explanation refers to this assignment to row.
row.id = "rows" + i; /* This assigns a new #id to the original not a clone
-- changed to `cln.id` */
When using a for loop leverage the incremental variable. When the clone was created, your references were still pointing to the original and it wasn't being used to increment anything so that's why it was just copying and not progressing.
Demo
Details commented in demo
<table id="xTable">
<tr id="xRow">
<td>First cell <input type="text" id="input" value="10012018"></td>
</tr>
</table><br>
<button onclick="xFunction()">Try it</button>
<script>
function xFunction() {
// In for loops declare i with let inside loop
// Start with 1 instead of 0 because you cloned the increment starting at 1000
for (let i = 1; i < 5; i++) {
var row = document.getElementById("xRow");
var cln = row.cloneNode(true);
// You are dealing with the clone not the original anymore
// Use i form increments
cln.id = "rows" + i;
// Target the clone specifically
// Use querySelector() to get #id, .class, or <tag>
var inpa = cln.querySelector("input");
// Once again var i to increment
inpa.id = "input" + i;
var a = parseFloat(document.getElementById("input").value);
// Remember i to increment but this is a little trickier
inpa.value = (a + (10000 * i));
document.getElementById("xTable").appendChild(cln);
}
}
</script>
Id's must be unique. Apply class to tr and input instead.
A generic solution
// n -> How many?
// start -> Start value
// index -> Index of value that should be incremented
// id -> Table id
function addRows(n, start, index, id) {
var table = document.getElementById(id);
for (var i = 2; i <= n + 1; i += 1) {
var arr = start.split("");
arr[index] = i.toString();
var incremented = arr.join("");
var tr = table.insertRow(-1);
tr.className = "row-" + i;
var cell = tr.insertCell(-1);
cell.textContent = "Cell ";
var span = document.createElement("span");
span.textContent = i + ": ";
var input = document.createElement("input");
input.className = "input-" + i;
input.value = incremented;
cell.appendChild(span);
cell.appendChild(input);
}
}
<table id="myTable">
<tr class="row-1">
<td>Cell <span>1: </span><input type="text" class="input-1" value="10012018"></td>
</tr>
</table><br>
<button onclick="addRows(5, '10012018', 3, 'myTable')">Try it</button>
<hr>
<table id="mySecondTable">
<tr class="row-1">
<td>Cell <span>1: </span><input type="text" class="input-1" value="14444"></td>
</tr>
</table><br>
<button onclick="addRows(8, '14444', 0, 'mySecondTable')">Try it</button>

add rows to table with JavaScript

I am trying to use JavaScript or ASP C# to add rows to a table in form when the user clicks the add row button. I have working code in JavaScript. I want to add the rows with text input boxes inside of the <td></td> tags. The row count is in my code becasue I am attempting to use it to add IDs to each element for use later.
element.innerHTML(<input id="tagcell"+(rowcount+1)+"" type="text"/>);
function addrow() {
var rowcount =
document.getElementById('tbl').getElementsByTagName('tbody').length;
window.alert(rowcount);
var tableRef = document.getElementById('tbl').getElementsByTagName('tbody')[0];
var newRow = tableRef.insertRow(tableRef.rows.length);
// Insert a cell in the row at index 0
var tagcell = newRow.insertCell(0);
var desccell = newRow.insertCell(1);
var loccell = newRow.insertCell(2);
var Namecell = newRow.insertCell(3);
var Sigcell = newRow.insertCell(4);
tagcell.innerHTML = "";
desccell.innerHTML="";
loccell.innerHTML = "";
Namecell.innerHTML="";
Sigcell.innerHTML = "";
}
<table id=tbl>
<tr>
<td id=tag_no>Col1</td>
<td id=desc> Col2</td>
<td id=loc> col3</td>
<td id=nme> col4</td>
<td id=sig> col5</td>
</tr>
</table>
<input type="button" value="clickme" onclick="addrow()" />
Here's how you could do that. (Obviously you can style the text boxes however you want.) Your code added the rows; I just added a textarea in each cell.
function addrow() {
var tableRef = document.getElementById('tbl').getElementsByTagName('tbody')[0];
var rowcount = tableRef.rows.length;
window.alert(rowcount);
var newRow = tableRef.insertRow(tableRef.rows.length);
var textBox = "<textarea></textarea>";
// Insert a cell in the row at index 0
var tagcell = newRow.insertCell(0);
var desccell = newRow.insertCell(1);
var loccell = newRow.insertCell(2);
var Namecell = newRow.insertCell(3);
var Sigcell = newRow.insertCell(4);
tagcell.innerHTML = textBox;
desccell.innerHTML= textBox;
loccell.innerHTML = textBox;
Namecell.innerHTML= textBox;
Sigcell.innerHTML = textBox;
}
<table id=tbl>
<tr>
<td id=tag_no>Col1</td>
<td id=desc> Col2</td>
<td id=loc> col3</td>
<td id=nme> col4</td>
<td id=sig> col5</td>
</tr>
</table>
<input type="button" value="clickme" onclick="addrow()" />
EDIT: Your row count shows the correct number now. (It was only showing 1 each time before.)
function addrow() {
var myTable = document.querySelector('#tbl');
var row = myTable .insertRow(0);
var cell1 = row.insertCell(0);
cell1.innerHTML = 'My first cell';
// and so on for other cells
}
p.s. please add "" to all your HTML attributes values. For example
<table id="tbl">

Javascript insert row into table after row with certain id

I have a table where each row has its unique id. Say there are rows with id='id25' and id='id26'. I need to insert a new row after row with id='id25'. I am using Vanilla JS without jQuery.
I have tried this:
var refElement = document.getElementById('id'+id);
var newrow = document.createElement("tr");
if (refElement) {
refElement.insertBefore(newrow, refElement.nextSibling);
}
but it throws me an error saying
Failed to execute 'insertBefore' on 'Node'
The node before which the new node is to be inserted is not a child of this node.
I know how to insert rows into top or bottom of the table but now I have an id as a reference to a particular row.
Any suggestions would be welcome
You want to insert into the refElement's parent, not refElement itself:
refElement.parentNode.insertBefore(newrow, refElement.nextSibling);
// -------^^^^^^^^^^^
var id = 1;
var refElement = document.getElementById('id' + id);
var newrow = document.createElement("tr");
newrow.innerHTML = "<td>new row</td>";
if (refElement) {
refElement.parentNode.insertBefore(newrow, refElement.nextSibling);
}
<table>
<tbody>
<tr id="id1"><td>refElement</td></tr>
<tr><td>original next sibling</td></tr>
</tbody>
</table>
(And yes, for anyone wondering, it'll work even if the refElement is the last row in the table.)
Inserting five rows per comment:
var id = 1;
var refElement = document.getElementById('id' + id);
var n, newrow;
if (refElement) {
for (n = 0; n < 5; ++n) {
newrow = document.createElement("tr");
newrow.innerHTML = "<td>new row #" + n + "</td>";
refElement.parentNode.insertBefore(newrow, refElement.nextSibling);
}
}
<table>
<tbody>
<tr id="id1">
<td>refElement</td>
</tr>
<tr>
<td>original next sibling</td>
</tr>
</tbody>
</table>
Note the order in which those appeared. If you want them in 0 - 4 order instead:
var id = 1;
var refElement = document.getElementById('id' + id);
var n, newrow;
if (refElement) {
for (n = 0; n < 5; ++n) {
newrow = document.createElement("tr");
newrow.innerHTML = "<td>new row #" + n + "</td>";
refElement.parentNode.insertBefore(newrow, refElement.nextSibling);
refElement = refElement.nextSibling; // *** This is the change
}
}
<table>
<tbody>
<tr id="id1">
<td>refElement</td>
</tr>
<tr>
<td>original next sibling</td>
</tr>
</tbody>
</table>
function addRowAfter(rowId){
var refElement = document.getElementById('id'+id);
var newrow= document.createElement('tr');
refElement.parentNode.insertBefore(newrow, refElement.nextSibling );
return newRow;
}
Check this.

Dynamic table from user input with cell id as grid reference

I am trying to create a table that is generated by user input data.
The table is reflecting a grid therfore I want the id of each cell to be the co ordinate of that grid. So the id of the bottom left cell would be id00. The top right cell id would be the maximum size of the grid that the user has entered.
So for example if data entered; x value=3; y value=3
this would produce the following table:
<table>
<tr><td id="id03"></td><td id="id13"></td><td id="id23"></td><td id="id33"></td></tr>
<tr><td id="id02"></td><td id="id12"></td><td id="id22"></td><td id="id32"></td></tr>
<tr><td id="id01"></td><td id="id11"></td><td id="id21"></td><td id="id31"></td></tr>
<tr><td id="id00"></td><td id="id10"></td><td id="id20"></td><td id="id30"></td></tr>
</table>
I have identified the basic concept for the code as you can see below:
<table>
Create a loop, initial value of r= 0; maximum value of r=y
r =0 <tr> create a secondary loop, initial value of n=0; maximum value of n = x; r remains constant for row
n=0; r= 0 <td id = “id” + “[x- (x-n)]” + “[y-r]” > </td>
….
n=3; r= 0* <td id = “id” + “[x- (x-n)]” + “[y-r]” > </td>
</tr>
….
r =3 <tr> n=0; r= 3 <td id = “id” + “[x- (x-n)]” + “[y-r]” > </td>
….
n=3; r= 3<td id = “id” + “[x- (x-n)]” + “[y-r]” > </td>
</tr>
</table>
I want to develop it in Javascript but I am new to the language and I am having trouble coding it.
Any help anyone could provide would be greatly appreciated.
Try this :
var x = 3; // value from input
var y = 4; // value from input
var table = document.getElementById("myTable");
for(var i = 0; i < y; i++) {
var row = table.insertRow(-1);
for(var j = 0; j < x; j++) {
var cell = row.insertCell(-1);
cell.id = "id" + (j) + (y - i - 1);
cell.innerHTML = cell.id;
}
}
​
Working example
Try something like this :
var rows = parseInt(document.getElementById('rows').value,10); // get input value
var cols = parseInt(document.getElementById('cols').value,10); // get input value
var table = document.createElement('table'); // create table element
table.border = "1"; // set some attributes
var prevrow; // used to store previous row element
for (var r = 0; r < (rows+1); r++) { // loop rows
var row = document.createElement('tr'); // create tr
for (var c = 0; c < (cols+1); c++) { // loop cols
var col = document.createElement('td'); // create td
col.id = 'id' + r + c; // set id of tr
col.innerHTML = col.id; // add some text
row.appendChild(col); // append td to tr
}
// if first tr then create append to table else insert before previous tr
if (prevrow) {
table.insertBefore(row, prevrow);
} else {
table.appendChild(row);
}
// store newly create tr
prevrow = row;
}
// append the new table to the output div
document.getElementById('output').appendChild(table);
Uses document.createElement(), element.appendChild() and element.insertBefore() to build the table
Working example here

Categories