Add Input to Each Column of HTML Table - javascript

I am trying to add an input field to each cell of my HTML table when I add a new row. The problem is that each time I click the button it only adds an input field to the first column. If I change the index number it only works for either the first or last column, but no columns in between.
<table id="table">
<tr>
<th id="item">Item</th>
<th>Ounces (Oz)</th>
<th>Grams (g)</th>
<th>Fluid Ounces (FOz)</th>
<th>Milliliters (mL)</th>
<th>Drops</th>
<th>Completed</th>
</tr>
</table>
<p>Click button to test funtionality.</p>
<button onclick="AddRow()">Click Me</button>
<script>
function AddRow() {
// Get ID for table from HTML file
var table = document.getElementById("table");
// Count number of columns in table
var columnNumber = document.getElementById("table").rows[0].cells.length;
// Add row to last row in table
var row = document.getElementById("table").insertRow(-1);
// Create Input field in table
var newInput = document.createElement("INPUT");
newInput.setAttribute("type", "text");
newInput.setAttribute("placeholder", "Raw Good Name");
newInput.classList.add("TableInput");
// Add columns to new row matching header
for (i = 1; i <= columnNumber; i++) {
var firstColumn = row.insertCell(0).appendChild(newInput);
}
}
</script>

Clone the input or simplify the script
I made the HTML valid and use an eventListener as recommended
const tb = document.getElementById("tb");
const columnNumber = document.querySelectorAll("#table thead tr th").length - 1;
const inp = '<td><input type="text" placeholder="Raw Good Name" class="TableInput"/></td>';
let cnt = 1;
document.getElementById("add").addEventListener("click",() => {
tb.innerHTML += `<tr>
<td class="right">${cnt++}</td>
${[...Array(columnNumber).keys()].map(i => inp).join("")}
</tr>`
})
.right {
text-align: right;
}
<table id="table">
<thead>
<tr>
<th id="item">Item</th>
<th>Ounces (Oz)</th>
<th>Grams (g)</th>
<th>Fluid Ounces (FOz)</th>
<th>Milliliters (mL)</th>
<th>Drops</th>
<th>Completed</th>
</tr>
<thead>
<tbody id="tb">
</tbody>
</table>
<p>Click button to test funtionality.</p>
<button type="button" id="add">Click Me</button>

You need to be creating the input and appending it to the cell within the loop that creates the cells so that more than one will be created.
/* This is only here for display purposes in the Stack Overflow environment */
input { width:5em; }
<table id="table">
<tr>
<th id="item">Item</th>
<th>Ounces (Oz)</th>
<th>Grams (g)</th>
<th>Fluid Ounces (FOz)</th>
<th>Milliliters (mL)</th>
<th>Drops</th>
<th>Completed</th>
</tr>
</table>
<p>Click button to test funtionality.</p>
<button onclick="AddRow()">Click Me</button>
<script>
function AddRow() {
// Get ID for table from HTML file
var table = document.getElementById("table");
// Count number of columns in table
var columnNumber = document.getElementById("table").rows[0].cells.length;
// Add row to last row in table
var row = document.getElementById("table").insertRow(-1);
// Add columns to new row matching header
// Loop should start at 0 and continue as long as you are less than
// the array length
for (i = 0; i < columnNumber; i++) {
// Create Input field in table
var newInput = document.createElement("INPUT");
// newInput.setAttribute("type", "text"); <-- Not needed: type="text" is the default
// newInput.setAttribute("placeholder", "Raw Good Name"); <-- See following line for simpler syntax
newInput.placeholder = "Raw Good Name";
newInput.classList.add("TableInput");
// If we're not on the first of last column
if(i !== 0 && i < columnNumber - 1){
newInput.type = "number"; // Make the input a number
}
row.insertCell(0).appendChild(newInput);
}
}
</script>

Related

How to insert row in table through Javascript function

I am trying to insert another row into a table with footer.
Here is my code:
function submit(){
/* Some code here with declarations & value assignings*/
let tble = document.getElementById("tabl");
let newEl = document.createElement("tr");
newEl.innerHTML="<td>"+nowSr+"</td> <td>"+taskForm+"</td> <td>"+tagForm+"</td> <td>Rs. "+amountForm+"</td>";
tble.appendChild(newEl, tble.lastElementChild.previousSibling.lastElementChild);
}
My function gives me below result:
As you can see (IN INSPECT ELEMENTS WINDOW) the new row is inserted after the footer. How to add it properly
after the last row in the table?
Don't insert the element directly to the <table> element, but select the <tbody> instead.
You can do that like that:
function submit(){
let tble = document.getElementById("tabl");
let newEl = document.createElement("tr");
newEl.innerHTML="<td>"+nowSr+"</td> <td>"+taskForm+"</td> <td>"+tagForm+"</td> <td>Rs. "+amountForm+"</td>";
tble.querySelector('tbody').appendChild(newEl, tble.lastElementChild.previousSibling.lastElementChild);
}
But you shouldn't use innerHTML to create the row (it could create an XSS vulnerability), use innerText or textContent instead. But that means that you have to create the <td>s differently:
function submit(){
let tble = document.getElementById("tabl");
let newEl = document.createElement("tr");
appendTD(newEl, nowSr);
appendTD(newEl, taskForm);
appendTD(newEl, tagForm);
appendTD(newEl, "Rs. "+amountForm);
tble.querySelector('tbody').appendChild(newEl, tble.lastElementChild.previousSibling.lastElementChild);
}
function appendTD(tr, text){
const td = document.createElement('td')
td.innerText = text
tr.appendChild(td)
}
Try puhsing to the tbody intead of the table directly
function addTableRow(){
const tbody = document.querySelector('#myTable tbody')
const newRow = document.createElement('tr')
newRow.innerHTML = `<td>Foo</td><td>Bar</td>`
tbody.appendChild(newRow)
}
<table id="myTable">
<thead>
<tr>
<th>Helo</th>
<th>World</th>
</tr>
</thead>
<tbody>
<tr>
<td>Foo</td>
<td>bar</td>
</tr>
</tbody>
</table>
<button onclick="addTableRow()">Add row</button>

How can I add <td> tags to my html table with JavaScript?

I'm trying to use the insertcell method to add a column to my table but either I'm getting the syntax wrong or it isn't working. I wondered if anyone could explain where I am going wrong?
The table body in the html is populated dynamically with some other JavaScript but I don't think this is the problem as I've tested grabbing some content from that table with an alert box and it works (commented out below):
<!DOCTYPE html>
<script type="text/javascript" src="fullstationxyparser.js">
</script>
<html>
<body>
<table border=1>
<thead>
<tr>
<td>Element Name</td>
<td>x</td>
<td>y</td>
<td>testCol</td>
</tr>
</thead>
<tbody id="stationlist">
</tbody>
</table>
</body>
</html>
function addStationNames() {
var myTable = document.getElementById("stationlist");
var stationListRows = myTable.getElementsByTagName('tr');
for (var i = 1; i < stationListRows.length; i++) {
var cell = stationListRows[i].getElementsByTagName('td');
var stationName = cell[0].innerHTML; //get station id from element Name column
var currentRow = stationListRows[i];
var newCol = currentRow.insertcell(-1);
newCol.innerHTML = stationName;
//alert(stationName);
}
}
In Firefox developer tools, I get TypeError: "currentRow.insertcell is not a function". Perhaps I can't use the insertcell method on a row collection?
In general you can call the insertRow() method on a Table DOM element, followed by calls to the insertCell() method as shown below to dynamically add <td> tags to your table with JavaScript.
Be careful to call insertCell() (with capital C) rather than insertcell() as you are currently doing:
const table = document.querySelector('table');
/* Insert new row */
const row = table.insertRow();
/* Insert cells (td) for row */
const td0 = row.insertCell(0);
const td1 = row.insertCell(1);
const td2 = row.insertCell(2);
const td3 = row.insertCell(3);
/* Populate cells with data */
td0.innerText = 'Foo';
td1.innerText = '3';
td2.innerText = '6';
td3.innerText = 'success';
<table border="1">
<thead>
<tr>
<td>Element Name</td>
<td>x</td>
<td>y</td>
<td>testCol</td>
</tr>
</thead>
<tbody>
</tbody>
</table>
Specific to your code, some other changes to consider might be as listed in this code snippet:
function addStationNames() {
/* Condense table row access into single query */
const stationRows = document.querySelectorAll("#stationlist tr");
stationRows.forEach((stationRow, i) => {
/* Skip first row */
if(i === 0) { return; }
/* Get station name from text of first cell */
const stationName = stationRow.querySelector('td:first-child').innerText;
/* Insert last cell on row and assign station name */
stationRow.insertCell(-1).innerText = stationName;
});
/*
Old code:
for (let i = 1; i < stationListRows.length; i++) {
var cell = stationListRows[i].getElementsByTagName('td');
var stationName = cell[0].innerHTML;
var currentRow = stationListRows[i];
var newCol = currentRow.insertcell(-1);
newCol.innerHTML = stationName;
}
*/
}
addStationNames();
<!-- set table id to stationlist -->
<table border="1" id="stationlist">
<thead>
<tr>
<td>Element Name</td>
<td>x</td>
<td>y</td>
<td>testCol</td>
</tr>
<tr>
<td>90's pop</td>
<td>232</td>
<td>543</td>
</tr>
</thead>
<tbody>
<!-- Remove id from tbody -->
</tbody>
</table>
An alternative to the answer above (which is totally fine) is this method, which is also a more general method of creating any html element:
const table = document.getElementById('one');
const newRow = document.createElement("tr");
let newCell = document.createElement("td");
newCell.textContent = "first cell";
let newCell2 = document.createElement("td");
newCell2.textContent = "second cell";
newRow.appendChild(newCell);
newRow.appendChild(newCell2);
table.appendChild(newRow);
https://jsfiddle.net/zgaosdbv/

Run function on all cells in table column with jQuery

I have a table element defined below as $table. I am trying to run a function on every cell a specific column that is defined by a specific table heading - qc_statusTh. I have found the index of that table heading (qc_statusColumnIndex) and have been able to grab the next table cell in that column - qc_statusCell.
However, I am not able to loop through the table cells and run a function on each table cell in that column.
Here is the JavaScript code I have so far:
$(document).ready(function() {
var $table = $("table.tables.list");
if ($table.length > 0) {
var qc_statusTh = $("th.headersub:contains('qc_status')");
var qc_statusColumnIndex = $(qc_statusTh).index();
var qc_statusCell = $($table).find("td").eq(qc_statusColumnIndex);
// this does not work. this only replaces the first cell
// in the row after qc_statusTh with "TESTING"
$(qc_statusCell).each(function() {
$(this).replaceWith("TESTING");
});
}
});
How can I edit this code to loop through each cell in the table that has an equal index to qc_statusColumnIndex?
If you think about it, you really want to iterate (using each) over the rows of the table, not the cells. If you do that, you can then grab the nth td element from each row and apply your transformation.
$(document).ready(function() {
var $table = $("table.tables.list");
if ($table.length > 0) {
var qc_statusTh = $("th.headersub:contains('qc_status')");
var qc_statusColumnIndex = $(qc_statusTh).index();
var qc_rows = $($table).find('tr');
$(qc_rows).each(function() {
$(this).find('td').eq(qc_statusColumnIndex).replaceWith("TESTING");
});
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table class="tables list">
<thead>
<th class="headersub">qc_example</th>
<th class="headersub">qc_status</th>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Ok</td>
</tr>
<tr>
<td>2</td>
<td>Ok</td>
</tr>
<tr>
<td>3</td>
<td>Error</td>
</tr>
</tbody>
</table>

Add table row programmatically doesn't work correctly in javascript

I have a form like that:
<form>
<table id="table">
<tr>
<th>Firstname</th>
<th>Lastname</th>
<th>SVNr</th>
</tr>
<tr>
<td contenteditable="true">Jill</td>
<td contenteditable="true">Smith</td>
<td class="svnr" contenteditable="true">50</td>
<td><input type="submit" value="Remove" onclick="DeleteRow(this)"></td>
</tr>
<tr>
<td contenteditable="true">Eve</td>
<td contenteditable="true">Jackson</td>
<td class="svnr" contenteditable="true">94</td>
<td><input type="submit" value="Remove" onclick="DeleteRow(this)"></td>
</tr>
</table>
<input type="button" value="Save Changes">
</form>
This one works perfectly. Futhermore, I want to add table rows to my table programmatically.
I do it this way:
count = numberOfRows;
formular[count] = new Object();
formular[count]["Firstname"] = document.getElementById("Firstname").value;
formular[count]["Lastname"] = document.getElementById("Lastname").value;
formular[count]["SVNr"] = document.getElementById("SVNr").value;
var table = document.getElementById("table");
var TR = table.insertRow(count);
var TD = document.createElement("td");
TD.setAttribute("contenteditable", "true");
var TD2 = document.createElement("td");
TD2.setAttribute("contenteditable", "true");
var TD3 = document.createElement("td");
TD3.setAttribute("contenteditable", "true");
TD3.className = "svnr";
var TD4 = document.createElement("td");
var TXT = document.createTextNode(formular[count]["Firstname"]);
var TXT2 = document.createTextNode(formular[count]["Lastname"]);
var TXT3 = document.createTextNode(formular[count]["SVNr"]);
var Input = document.createElement("input");
Input.type = "submit";
Input.value = "Remove";
Input.onclick = "DeleteRow(this);";
TD.appendChild(TXT);
TR.appendChild(TD);
TD2.appendChild(TXT2);
TR.appendChild(TD2);
TD3.appendChild(TXT3);
TR.appendChild(TD3);
TD4.appendChild(Input);
TR.appendChild(TD4);
document.getElementById("Firstname").value = "";
document.getElementById("Lastname").value = "";
document.getElementById("SVNr").value = "";
Also this code is working well. The only problem is that the Remove function doesn't work correctly for the table rows I added programmatically.
My Removing function looks like that:
function DeleteRow(o) {
var p = o.parentNode.parentNode;
p.parentNode.removeChild(p);
}
This function removes ALL programmatically added values if I press the button for one of them. This function works for the 2 entries in the form I didn't add programmatically but as I said, if I press the Remove button for one of added entries, it removes all programmatically added rows and not just the chosen one.
You need to add in something to uniquely identify each tr. You could set a custom attribute on each tr, set a unique id, etc. and pass the unique value to the delete function.
In addition you may find it easier to work with tables by using the DOMTable properties & methods:
http://www.javascriptkit.com/domref/tableproperties.shtml
http://www.javascriptkit.com/domref/tablemethods.shtml

Filtering table rows upon Search

I am trying to filter the rows of a table to display the results of entered text in the search bar. The code below does the job but for some reason filters the column headings as well.
$('#search').keyup(function () {
var data = this.value.split(" ");
var rows = $(".Info").find("tr").hide();
if(this.value ==""){
rows.show();
return;
}
rows.hide();
rows.filter(function(i,v){
var t = $(this);
for (var d = 0; d < data.length; d++) {
if (t.is(":Contains('" + data[d] + "')")) {
return true;
}
}
return false;
}).show();
});
HTML
<input type = "search" name = "search" id = "search">
<table style ="width:95%" class = "Info">
<tr>
<th>Select </th>
<th>Name</th>
<th>Number</th>
<th>Date</th>
</tr>
</table>
The user adds rows which is why i haven't written any HTML for it.
Any help would be appreciated. Thanks in advance
http://jsfiddle.net/szjhngwm/
It looks like you need to filter using tbody
<table style ="width:95%" class = "Info">
<thead>
<tr>
<th>Select </th>
<th>Name</th>
<th>Number</th>
<th>Date</th>
</tr>
<thead>
<tbody>
</tbody>
</table>
var rows = $(".Info tbody tr").hide();
Another way to do this would be to use jQuery's :gt() selector.
The only thing that would change is this line:
var rows = $(".Info").find("tr:gt(0)").hide();
Notice the addition of :gt(0) to your tr.

Categories

Resources