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>
Related
I want to manipulate (add/delete rows) for two tables in html using JavaScript. With one it works, but if I add the second one I get this error:
Uncaught TypeError: Cannot set property 'innerHTML' of null
More precisely: I want to have two tables each with different content based on which button is clicked.
With one table it worked. The first function deleted table content -> added new content. Second function the same, deleted content from first table -> added its new content.
But I want to do this with two tables. Please let me know how it should be done.
function First(tableID, tableID2) {
let table = document.getElementById(tableID)
table.innerHTML = ""; // here is the mentioned error.
// I would like to have something like..
// let table2 = document.getElementById(tableID2)
// table2.innerHTML = "";
}
<p>Click the button to add a new row at the first position of the table and then add cells and content</p>
<table id="myTable">
<TR>
</TR>
</table>
<table id="myTable2">
<TR>
</TR>
</table>
<br>
<button type="button" id="first" onclick="First(myTable, myTable2)">First</button>
<button type="button" id="second" onclick="Second(myTable, myTable2)">Second</button>
If you don't wrap myTable and myTable2 in quotations, JavaScript assumes it is an object. Since you didn't define myTable nor myTable2, they are null. You can't modify the innerHTML of null, and thus you get the error "Cannot set property 'innerHTML' of null".
In the example below, the names are wrapped in quotations which makes it a String:
function First(tableID, tableID2) {
let table = document.getElementById(tableID)
table.innerHTML = "<tr>first</tr>"; // here is the mentioned error.
let table2 = document.getElementById(tableID2)
table2.innerHTML = "<tr>first again</tr>";
}
function Second(tableID, tableID2) {
let table = document.getElementById(tableID)
table.innerHTML = "<tr>second</tr>"; // here is the mentioned error.
let table2 = document.getElementById(tableID2)
table2.innerHTML = "<tr>second again</tr>";
}
<p>Click the button to add a new row at the first position of the table and then add cells and content</p>
<table id="myTable">
<TR>
</TR>
</table>
<table id="myTable2">
<TR>
</TR>
</table>
<br>
<button type="button" id="first" onclick="First('myTable', 'myTable2')">First</button>
<button type="button" id="second" onclick="Second('myTable', 'myTable2')">Second</button>
Alternatively, you could define the two variables before they are referenced:
function First(tableID, tableID2) {
let table = document.getElementById(tableID)
table.innerHTML = "<tr>first</tr>"; // here is the mentioned error.
let table2 = document.getElementById(tableID2)
table2.innerHTML = "<tr>first again</tr>";
}
function Second(tableID, tableID2) {
let table = document.getElementById(tableID)
table.innerHTML = "<tr>second</tr>"; // here is the mentioned error.
let table2 = document.getElementById(tableID2)
table2.innerHTML = "<tr>second again</tr>";
}
<p>Click the button to add a new row at the first position of the table and then add cells and content</p>
<table id="myTable">
<TR>
</TR>
</table>
<table id="myTable2">
<TR>
</TR>
</table>
<br>
<script>
var myTable = 'myTable';
var myTable2 = 'myTable2';
</script>
<button type="button" id="first" onclick="First(myTable, myTable2)">First</button>
<button type="button" id="second" onclick="Second(myTable, myTable2)">Second</button>
just add some quotation mark on your args when calling your function. Otherwise, javascript think "myTable" is a variable, which doesn't exists.
<button type="button" id="first" onclick="First('myTable', 'myTable2')">First</button>
Were you trying to use just one function to edit both tables? Here's a version of that. Just pass in the ID of the table with a string.
function eTable(tableID) {
let table = document.getElementById(tableID)
let row = table.insertRow(0);
let cell = row.insertCell(0);
cell.innerHTML = "New cell for " + tableID;
}
<p>Click the button to add a new row at the first position of the table and then add cells and content</p>
Table 1:
<table id="myTable">
<TR>
</TR>
</table>
Table 2:
<table id="myTable2">
<TR>
</TR>
</table>
<br>
<button type="button" id="first" onclick="eTable('myTable')">First</button>
<button type="button" id="second" onclick="eTable('myTable2')">Second</button>
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>
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
}
}
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
I was trying to add a table row with data in my HTML table using Javascript but it seems I it can't add. Why is that?
<html>
<head>
<title>
</title>
<script>
function addUser(){
var tbl = document.getElementById('datatable');
var lastRow = tbl.rows.length;
var iteration = lastRow+1;
var row = tbl.insertRow(lastRow);
var cellLeft = row.insertCell(0);
var textNode = document.createTextNode(iteration);
cellLeft.appendChild(textNode);
}
</script>
</head>
<body>
<table border = 1 id = "datatable">
<tr>
<td>ID</td>
<td>NAME</td>
<td>ADDRESS</td>
</tr>
<tr>
<td>1</td>
<td>Something</td>
<td>Something</td>
</tr>
<tr>
<td>2</td>
<td>Foo</td>
<td>bar</td>
</tr>
</table>
<form id = "myForm" onsubmit = "addUser()">
ID:<input type = "text" name = "txtID"><br />
NAME:<input type = "text" name = "txtName"><br />
ADDRESS:<input type = "text" name = "txtAddress"><br />
<input type = "submit" value = "Add Item">
</form>
</body>
</html>
what you need is not to submit a form
just simply an onclick event could help.
<input type = "button" value = "Add Item" onclick="addUser()">
It's because you're submiyting a form. First your AddUSer is called and works, but the page is reloaded and what you see is the initial page.