javascript Insert a new row in a table with 2 headers - javascript

I have a table that looks like this :
<button onclick="addRow()">Add a Row</button>
<table id="mytable">
<tr>
<th colspan="3">My header</th>
<tr>
<tr>
<th>header</th>
<td>cell1</td>
<td>cell2</td>
</tr>
</table>
And I am trying to create a javascript function to add new rows to the table that would match the last row.
<script>
function addRow() {
var table = document.getElementById("mytable");
var rows = table.getElementsByTagName("tr").length;
var row = table.insertRow(rows);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
cell1.innerHTML = "header";
cell2.innerHTML = "cell1";
cell3.innerHTML = "cell2";
}
</script>
After spending a good amount of time on google trying to figure it out. I must say I could not find what I am looking for. Any help would be much appreciated.

Your problem is that insertCell() only creates <td> tags, so you need to use document.createElement to create the <th> tag for your first cell.
<button onclick="addRow()">Add a Row</button>
<table id="mytable">
<tr>
<th colspan="3">My header</th>
<tr>
<tr>
<th>header</th>
<td>cell1</td>
<td>cell2</td>
</tr>
</table>
<script>
function addRow() {
var table = document.getElementById("mytable");
var rows = table.getElementsByTagName("tr").length;
var row = table.insertRow(rows);
var cell1 = document.createElement("TH");
row.appendChild(cell1);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2);
cell1.innerHTML = "header";
cell2.innerHTML = "cell1";
cell3.innerHTML = "cell2";
}
</script>

Related

Saving input from modal to one of three different tables

I have 3 tables in a div that I want to make editable. At the bottom of each table there is an "add" button that opens a modal (they all open the same modal). I have the following JS to add new rows:
How do I get the JS to know which of the three tables to add the row to? The three tables I have are acc_table1, acc_table2, acc_table3. I tried "var table = document.getElementById("acc_table"+no);" which did not work.
if (tit.innerHTML === "Add Account"){
var table = document.getElementById("acc_table1");
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = document.getElementById("modal_type").value;
cell2.innerHTML = document.getElementById("modal_price").value;
}
You can do this by considering the context in which the button is clicked. We can use Node.previousElementSibling() or Element.closest() to search for the relevant table (depending on the structure of your DOM), in which the new row should be inserted. In that case, you won't need to pass parameters/arguments to the callback, which will require that you keep track of new IDs and etc.
If your <button> element is immediately after the <table> element, then you can use e.target.previousElementSibling to select the <table> element of interest, when the click event is fired on the button element:
document.querySelectorAll('.addAccount').forEach(function(el) {
el.addEventListener('click', function(e) {
// Table element is immediately before button
var table = e.target.previousElementSibling;
// Perform sanity check before proceeding
if (!table || !table.matches('table'))
return;
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = document.getElementById("modal_type").value;
cell2.innerHTML = document.getElementById("modal_price").value;
});
});
<input type="text" id="modal_type" value="MODAL_TYPE" />
<input type="text" id="modal_price" value="MODAL_PRICE" />
<h1>Table 1</h1>
<table>
<tbody></tbody>
</table>
<button type="button" class="addAccount">Add account</button>
<h1>Table 2</h1>
<table>
<tbody></tbody>
</table>
<button type="button" class="addAccount">Add account</button>
<h1>Table 3</h1>
<table>
<tbody></tbody>
</table>
<button type="button" class="addAccount">Add account</button>
Alternatively, if your <button> element is wrapped in a same parent element (say, a <div> element), then you can use a combination of Element.closest() and Element.querySelector() to find the table in the same parent. Again, no ID is required and all is based on contextual information from DOM hierarchy:
document.querySelectorAll('.addAccount').forEach(function(el) {
el.addEventListener('click', function(e) {
// Table element is immediately before button
var table = e.target.closest('.wrapper').querySelector('table');
// Perform sanity check before proceeding
if (!table)
return;
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = document.getElementById("modal_type").value;
cell2.innerHTML = document.getElementById("modal_price").value;
});
});
<input type="text" id="modal_type" value="MODAL_TYPE" />
<input type="text" id="modal_price" value="MODAL_PRICE" />
<hr />
<div class="wrapper">
<button type="button" class="addAccount">Add account</button>
<p>Random text here</p>
<h1>Table 1</h1>
<table>
<tbody></tbody>
</table>
</div>
<div class="wrapper">
<h1>Table 2</h1>
<table>
<tbody></tbody>
</table>
<p>Random text here</p>
<button type="button" class="addAccount">Add account</button>
</div>
You can use a variable to store desired table ID to use it when you want to save the data to table.
Something along like the example below
var tableId = "";
function openModalFunction(selectedTableId){
tableId = selectedTableId;
}
function saveDataToTable(){
var table = document.getElementById(tableId);
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = "cell 1";
cell2.innerHTML = "cell 2";
}
<table id="acc_table1">
<thead><tr><th colspan=2>Table 1</th></tr></thead>
<tfoot>
<tr>
<th colspan=2>
<button onclick="openModalFunction('acc_table1')">table one</button>
</th>
</tr>
</tfoot>
</table>
<hr>
<table id="acc_table2">
<thead><tr><th colspan=2>Table 1</th></tr></thead>
<tfoot>
<tr>
<th colspan=2>
<button onclick="openModalFunction('acc_table2')">table two</button>
</th>
</tr>
</tfoot>
</table>
<hr>
<button onclick="saveDataToTable()">Save</button>

Storing data in a table

I am trying to create a user table for my website, where the user can see their first name and last name in a table after they register and login. The user detail is stored in the HTML5 Local Storage. Is there a better way to update the table with more users, rather than creating more .
Here is my table:
<table id="rankTable">
<tr>
<th>First Name</th>
<th>Last Name</th>
<th>Top Score</th>
</tr>
<tr>
<td id="_firstName"></td>
<td id="_lastName"></td>
<td></td>
</tr>
</table>
Here is the full working snippet: https://jsfiddle.net/MuddasarAshfaq/r62zmjw4/9/
Assuming that u have stored your stored firstname and lastname as "fname" and "lname" in your localStorage
var table = document.getElementById("rankTable");
var row = table.insertRow(0);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = localStorage.getItem("fname");
cell2.innerHTML = localStorage.getItem("lname");

How to add dynamically html table data in mysql database using PHP?

I have following code, with java script code for add dynamically rows to table and add values as table data,
but i'm unable to add data into a database. It contains with add button function.Right now the code does not insert data to the database. So,i need to add dynamically html data into mysql database with using PHP code
<html>
<head>
<SCRIPT language="javascript">
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var cell1 = row.insertCell(0);
var element1 = document.createElement("input");
element1.type = "text";
element1.name="txtbox[]";
cell1.appendChild(element1);
var cell1 = row.insertCell(0);
var element1 = document.createElement("input");
element1.type = "text";
element1.name="txtbox[]";
cell1.appendChild(element1);
var cell1 = row.insertCell(0);
var element1 = document.createElement("input");
element1.type = "text";
element1.name="txtbox[]";
cell1.appendChild(element1);
}
</script>
</head>
<div id="table_wrapper">
<table class="meta">
<tr id="noExl"
<th><span contenteditable>Invoice #</span></th>
<td><span contenteditable>101138</span></td>
</tr>
<tr id="noExl">
<th><span contenteditable>Date</span></th>
<td><span contenteditable>January 1, 2012</span></td>
</tr>
<tr id="noExl">
<th><span contenteditable>Amount Due</span></th>
<td><span id="prefix" contenteditable>Rs</span>
<span>600.00</span></td>
</tr>
</table>
<table class="inventory" id="dataTable">
<thead>
<tr id="noExl">
<th><span contenteditable>Item</span></th>
<th><span contenteditable>Description</span></th>
<th><span contenteditable>Amount</span></th>
</tr>
</thead>
<tbody>
<tr id="noExl">
<td><a class="cut">-</a><span contenteditable>Front End
Consultation</span></td>
<td><span contenteditable>Experience Review</span></td>
<td><input onblur="findTotal()" type="text" name="qty"
id="qty1"/></td>
</tr>
</tbody>
<tbody>
</tbody>
</table>
<INPUT type="button" value="+" onclick="addRow('dataTable')" />
I am supposing that you have ready to post data in database
Grab you all values in a java script function
Post these values using ajax
I am attaching a sample ajax method, you can modify it as per own requirements
//call to remote update function
update_table(var1,var2);
//method definition
function update_table(var1,var2){
var action_post_data='id='+var1+'&total'+var2;
jQuery.ajax({
url: 'update/table',
type: 'POST',
data: action_post_data,
dataType: 'json',
success: function (data) {
//do something
}
},
error: function () {
//do something
}
}

Add row into existing table

May I know how do I insert items into my table body? My code doesn't seems to work.
var tableRef = document.getElementById("myList").getElementsByTagName("tbody");
var newRow = tableRef.insertRow(tableRef.rows.length);
var newCell = tableRef.insertCell(0);
var myTextTwo = "hello world";
var newText = document.createTextNode(myTextTwo);
newCell.appendChild(newText);
<table id="myList">
<thead>
<tr>
<td>Product ID</td>
<td>Product Name</td>
<td>Quantity</td>
</tr>
</thead>
<tbody>
</tbody>
</table>
getElementsByTagName returns an array. You need to append [0] to select the first element in the array.
You are also trying to use insertCell on tableRef, when you should be using it on newRow:
var tableRef = document.getElementById("myList").getElementsByTagName("tbody")[0];
var newRow = tableRef.insertRow(tableRef.rows.length);
var newCell = newRow.insertCell(0);
var myTextTwo = "hello world";
var newText = document.createTextNode(myTextTwo);
newCell.appendChild(newText);
<table id="myList">
<thead>
<tr>
<td>Product ID</td>
<td>Product Name</td>
<td>Quantity</td>
</tr>
</thead>
<tbody>
</tbody>
</table>
To make it work, you need to:
1) Put [0] after .getElementsByTagName() like below, as this method returns an array of elements, unlike .getElementById(), which returns the first instance:
var tableRef = document.getElementById("myList").getElementsByTagName("tbody")[0];
2) Use the .insertCell() in the row you want the cell to be, in our case newRow, not on the table's tbody:
var newCell = newRow.insertCell(0);
Your correct JavaScript code should be:
var tableRef = document.getElementById("myList").getElementsByTagName("tbody")[0];
var newRow = tableRef.insertRow(tableRef.rows.length);
var newCell = newRow.insertCell(0);
var myTextTwo = "hello world";
var newText = document.createTextNode(myTextTwo);
newCell.appendChild(newText);
You can also check out the following snippet:
var tableRef = document.getElementById("myList").getElementsByTagName("tbody")[0];
var newRow = tableRef.insertRow(tableRef.rows.length);
var newCell = newRow.insertCell(0);
var myTextTwo = "hello world";
var newText = document.createTextNode(myTextTwo);
newCell.appendChild(newText);
#myList {
border: 1px solid black;
}
#empty {
border-bottom: 1px solid black;
}
<table id = "myList">
<thead>
<tr>
<td>Product ID</td>
<td>Product Name</td>
<td>Quantity</td>
</tr>
<!--- This row is for adding a border-bottom line -->
<tr>
<td id = "empty" colspan ="3"></td>
</tr>
</thead>
<tbody>
</tbody>
</table>

Javascript: extract cell data from table

I have a scenario where there is a table of 4 rows, in the 4th row is a textbox. When an "onchange" event of the textbox is triggered, I want to extract the data in the cells of the same specific row into another table. and ofcourse my table is consisted of more than one row.
<div class="ProductsTable">
<table class="tablestyle">
<tr>
<th>Item</th>
<th>Price</th>
<th>Preview</th>
<th class="auto-style4">Quantity</th>
<th class="auto-style15">Selected Items</th>
</tr>
<tr id="row1">
<td class="auto-style1" id="item_name">Sofa</td>
<td class="auto-style2" id="item_price">$280.00</td>
<td class="auto-style3">
<img class="itemimage" src="images\sofa1.jpg" />
</td>
<td class="auto-style4">
<input class="quantitybox" id="item_quantity" type="text" onchange="get_quantity();" />
</td>
<td rowspan="10">
<table class="InvoiceTable" id="invoice">
<tr>
<th class="auto-style7">Item</th>
<th class="auto-style2">Price</th>
<th class="auto-style4">Quantity</th>
</tr>
</table>
</td>
</tr>
</table>
</div>
And my javascript is:
function get_quantity() {
var table = document.getElementById("invoice");
var row = table.insertRow(1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
var cell3 = row.insertCell(2)
cell1.innerHTML = document.getElementById("item_name").innerHTML;
cell2.innerHTML = document.getElementById("item_price").innerHTML;
cell3.innerHTML = document.getElementById("item_quantity").value;
}
How can I create a loop to check through all my table when an "onchange" event is triggered. As I actually have 10 rows in my table.
Preferably without using jquery.
If I understand you correctly you are looking for a function to copy the content of the changed row, that is the data in each column, into the invoice table.
I expect the rows to be created dynamicaly with some sort of iteration. When iterating I expect a unique number is availabe why this can be used as a general selector.
Here is a function to do this:
function get_quantity(rowNumber) {
var table = document.getElementById("invoice" + rowNumber);
var row = table.insertRow(1);
var columns = document.getElementById("row" + rowNumber).childNodes;
var dataColumnIndex = 0;
for (var i = 0; i < columns.length; i++) {
if (columns[i].className == "data") {
var cell = row.insertCell(dataColumnIndex);
cell.innerHTML = columns[i].innerHTML;
dataColumnIndex++;
}
}
var inputQuantity = document.getElementById("item_quantity" + rowNumber).value
row.insertCell(dataColumnIndex).innerHTML = inputQuantity;
}
You select what columns to copy by marking the them with class data.
I gets the invoice table by expecting it to have the id invoice + number. Fx. invoice1. Same goes with each row and the input field.
Here is a plunker with a full example.
Edit
There should only be a single invoice table where all products are added to.
By selecting the same table for row insertion in the function this is fixed.
This updated plunker has the change

Categories