JavaScript Restart Counter - javascript

I am probably overthinking the question, but how do I restart a counter? Also, as you will see in my code, the counter is supposed to match but doesn't. I want the cell to have a shared value of the row that it is in, for example the first rows cells should have the ID: cell 0.0, cell 0.1, but rather it has skipped one where the first number is one row ahead.
var rowCount = 0;
var cellCount = 0;
function appendRow(id, style) {
var table = document.getElementById(id); // table reference
length = table.length,
row = table.insertRow(table.rows.length); // append table row
row.setAttribute('id', style);
var i;
row.id = 'row' + rowCount;
rowCount++
console.log(rowCount, cellCount);
// insert table cells to the new row
for (i = 0; i < table.rows[0].cells.length; i++) {
createCell(row.insertCell(i), i, 'cell ' + rowCount + '.' + cellCount); // doesn't start over once row changes
cellCount++
}
}
function createCell(cell, text, style) {
var div = document.createElement('div'), // create DIV element
txt = document.createTextNode('_'); // create text node
div.appendChild(txt); // append text node to the DIV
div.setAttribute('id', style); // set DIV class attribute
div.setAttribute('idName', style); // set DIV class attribute for IE (?!)
cell.appendChild(div); // append DIV to the table cell
}
table {
text-align: center;
}
td {
width: 100px;
}
<button id="addCust" class="addSort" onclick="appendRow('custList')">add customer</button>
<div class="custScroll">
<table id="custListTop" contenteditable="false">
<tr>
<td style="border-top-left-radius: 5px;">Customers</td>
<td style="border-top-right-radius: 5px;">Main Location</td>
</tr>
</table>
<table id="custList" contenteditable="true">
<tr>
<td>Someone</td>
<td>something</td>
</tr>
</table>
</div>

I'm not sure this is what you want, but if you put rowCount++ after the for loop it starts off the first element at 0 then increments from there.
If you want the cells to start over then change createCell to use i instead of cellCount:
createCell(row.insertCell(i), i, 'cell ' + rowCount + '.' + i);

Related

Preserve HTML table location after dynamic update

When I update an HTML table using appendChild(), the entire table is moved to the bottom of the document. How do I preserve the location of the table in the DOM?
My example is also posted on JSFiddle.
<!--I want the existing table below to stay fixed in place after new rows are added.-->
<table id="table">
<tr>
<td> Table Cell 1</td>
<td> Table Cell 2</td>
</tr>
</table>
<!--The following button will add rows, but also move the table. How do I stop the move?-->
<input type="button" value="ADD NEW ROWS." onclick="generate_table()">
<script>
// This function just creates new rows for the table
function generate_table() {
var body = document.getElementsByTagName("body")[0];
var tbl = document.getElementById("table");
var tblBody = document.createElement("tbody");
for (var i = 0; i < 2; i++) {
var row = document.createElement("tr");
for (var j = 0; j < 2; j++) {
var cell = document.createElement("td");
var cellText = document.createTextNode("cell " + i + ", column " + j);
cell.appendChild(cellText);
row.appendChild(cell);
}
tblBody.appendChild(row);
}
tbl.appendChild(tblBody);
body.appendChild(tbl);
}
</script>
<style>
table,
th,
td {
border: 1px solid black;
border-collapse: collapse;
}
</style>
Remove the following line, you don't need it.
body.appendChild(tbl);
The table node is already a part of the Document Object Model, you don't need to add it again. By appending the element to body, you are moving it from the current position to the end of the body node.
As a rule of thumb, you need to use appendChild, only if the element was created dynamically using createElement.

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.

Button not rendering where expected

I am clicking a button in my HTML and expecting a table to be created with X amount of rows depending on the for loop and then at the end of each row a button.
I am expecting the output to look like this:
<table>
<tr>
<td> first element </td>
<button> </button>
</tr>
<tr>
<td> first element </td>
<button> </button>
</tr>
</table>
However for some reason the button does not render on the first row:
<table>
<tr>
<td> first element </td>
</tr>
<tr>
<td> first element </td>
<button> </button>
</tr>
</table>
This is the code I am using:
function makeHTMLMatchesTable(array){
var table = document.createElement('table');
var button = document.createElement('button');
button.setAttribute("id", "unMatchButton");
console.log(array.length, 'ARRAY');
for (var i = 0; i < array.length; i++) {
console.log(array[i], 'ai');
var row = document.createElement('tr');
var cell = document.createElement('td');
cell.textContent = array[i];
row.appendChild(cell);
row.appendChild(button);
table.appendChild(row);
}
return table;
}
I am expecting the output to look like this
The structure you quote is invalid. You can't have button as a direct child of tr. From the spec for tr, the only things that can be in a tr element are td, th, or script-supporting elements.
However for some reason the button does not render on the first row:
Because you've only created one button element, and then appended it to two separate rows. Appending it doesn't clone it, it moves it from its old parent (if any) to a new one.
To fix it:
Create a new button each time you want a new button (with a new id; id values must be unique in a document).
Append the button to a td, not to a tr.
Example:
function makeHTMLMatchesTable(array) {
var table = document.createElement('table');
for (var i = 0; i < array.length; i++) {
var row = document.createElement('tr');
var cell = document.createElement('td');
cell.textContent = array[i];
row.appendChild(cell);
cell = document.createElement('td'); // Second td
var button = document.createElement('button'); // New button for each
button.setAttribute("id", "unMatchButton" + i); // Unique id
cell.appendChild(button); // Button in cell
row.appendChild(cell); // Add second cell
table.appendChild(row);
}
return table;
}
document.body.appendChild(
makeHTMLMatchesTable(["one", "two", "three"])
);
you need to create a new button for each row
function makeHTMLMatchesTable(array){
var table = document.createElement('table');
console.log(array.length, 'ARRAY');
for (var i = 0; i < array.length; i++) {
console.log(array[i], 'ai');
var row = document.createElement('tr');
var cell = document.createElement('td');
cell.textContent = array[i];
var button = document.createElement('button');
button.setAttribute("id", "unMatchButton");
row.appendChild(cell);
row.appendChild(button);
table.appendChild(row);
}
return table;
}

Add rows and data

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";

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