I am trying to give a dynamic row number while clicking add and delete button, but in between I delete any row it is not giving proper row_number.
My td in table(dataTable) is:
echo "<td> 1 <input type='hidden' name='task_number[]' value='1'> </td>";
ADD and delete btn :
echo "<input type='button' value='Add Task' onClick=addRow('dataTable') /> ";
echo "<INPUT type='button' value='Delete Task' onclick=deleteRow('dataTable') />";
in javascript:
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length -1;
var inps = document.getElementsByName('task_number[]');
var inp=inps[rowCount-1].value; // array start from 0
inp = ++inp;
var cell2 = row.insertCell(1);
cell2.innerHTML = inp;
}
Output
use this function
function setRowNumber()
{
$('#tablename tbody tr').each(function (idx) {
$(this).children("td:eq(1)").html(idx + 1);
});
}
I also put a dynamic table code. If the checkbox is checked, that row can be deleted.
orderTable();
function addRow()
{
var rowCount = $('#example tr').length;
if(rowCount == 1)
{
var tr = "<tbody><tr id='tr'><td><input type='checkbox' id='chk' name='chk' value='chk'></td>" + "<td></td><td>Task Designer</td></tr></tbody>";
$('#example thead:last').after(tr);
}
else
{
var tr = "<tr id='tr'><td><input type='checkbox' id='chk' name='chk' value='chk'></td>" + "<td></td><td>Task Designer</td></tr>";
$('#example tr:last').after(tr);
}
orderTable();
}
function deleteRow()
{
var i = 0;
$('#example input[type=checkbox]').each(function(){
if($(this).is(":checked"))
{
$('#tr' + (i + 1)).remove();
}
i = i + 1;
});
$('#example input[type=checkbox]').each(function(){
$(this).prop('checked', false);
});
orderTable();
}
function orderTable()
{
var rowCount = $('#example tbody tr').length;
if(rowCount > 0)
{
$('#example tbody tr').each(function (idx) {
var num = idx + 1;
$(this).children("td:eq(1)").html(num);
$(this).children("td:eq(2)").html('Task Designer' + num);
$(this).attr('id','tr' + num);
//set input names
$(this).children("td:eq(0)").children().attr('id','chk' + num);
$(this).children("td:eq(0)").children().attr('name','chk' + num);
$(this).children("td:eq(0)").children().attr('value','chk' + num);
});
}
}
#example
{
border:1px solid #ddd;
border-collapse: collapse;
}
th
{
background:#333;
color:white;
font-weight:bold;
height:40px;
}
td
{
text-align: center;
vertical-align: middle;
border:1px solid #ddd;
height:40px;
}
<input type='button' id="btnAdd" value='Add Task' onclick="addRow()" />
<input type='button' id="btnRemove" value='Delete Task' onclick="deleteRow()" />
<table id="example" class="display" cellspacing="0" width="100%" border="0">
<thead>
<tr>
<th>Select</th>
<th>Task Number</th>
<th>Task Description</th>
</tr>
</thead>
<tbody>
<tr id="tr">
<td><input type="checkbox" id="chk" name="chk" value="chk"></td>
<td>11</td>
<td>Task Designer</td>
</tr>
<tr id="tr">
<td><input type="checkbox" id="chk" name="chk" value="chk"></td>
<td>2</td>
<td>Task Designer</td>
</tr>
<tr id="tr">
<td><input type="checkbox" id="chk" name="chk" value="chk"></td>
<td>3</td>
<td>Task Designer</td>
</tr>
</tbody>
</table>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
Related
I’ve searched and consulted a lot of code but nothing is helping me to fix my problem.
What I have is just "add rows", but I want also the sum after adding the rows.
Here is a part of my code that adds a row to a table:
Code for adding rows
$(document).ready(function () {
$(".add-row").click(function () {
var name = $("#name").val();
var email = $("#email").val();
var markup = "<tr><td style='text-align:center'><input type='checkbox' name='record'></td><td>" + email + "</td><td class='sum_me' style='text-align: right;'>" + name + "</td></tr>";
$("table tbody").append(markup);
});
});
Html
<table id="countit">
<thead>
<tr>
<th width=50px>Delete</th>
<th width=150px style="text-align: center;">Inpayment of:</th>
<th width=50px style="text-align: center;">AMOUNT :</th>
</tr>
</thead>
<tbody>
<tr></tr>
</tbody>
</table>
<input type="button" class="btn-success" value="Save Transaction" style="width: 150px; float: right;">
<br>
<br>
Create a function that sums the values and shows the result. call it after adding the row to the table.
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<script>
function updateSum(){
var sum = 0;
$('.sum_me').each(function(item, index){
sum = sum + $(item).text();
});
$('#total').text(sum);
}
$(document).ready(function(){
$(".add-row").click(function(){
var name = $("#name").val(); // input text
var email = $("#email").val(); // input text
var markup = "<tr><td style='text-align:center'><input type='checkbox' name='record'></td><td>" + email + "</td><td class='sum_me' style='text-align: right;'>" + name + "</td></tr>";
$("table tbody").append(markup);
updateSum();
});
});
</script>
You can use tfooter after the tbody to hold this total value
<table id="countit">
<thead>
<tr>
<th width=50px>Delete</th>
<th width=150px style="text-align: center;">Inpayment of:</th>
<th width=50px style="text-align: center;">AMOUNT :</th>
</tr>
</thead>
<tbody>
<tr>
</tr>
</tbody>
<tfoot>
<tr><td></td><td></td><td id="total"></td></tr>
</tfoot>
</table>
<input type="button" class="btn-success" value="Save Transaction" style="width: 150px; float: right;">
I have an html code with multiple rows containing two values.Using javascript,I am able to compare the two values for only one row.How can I do the same for dynamically generated rows.
HTML:
<tbody id="appendrow" class="appendrow">
<input type="text"
data-field="quantity"
required
class="form-control"
name="units_ordered[]"
id="units_ordered0"
value=""/>
<input type="text"
data-field="inventory"
class="form-control"
name="inventory"
id="inventory0"
value="" />
</tbody>
Javascript:
var counter = 1;
$(window).load(function () {
$(function () {
$('#addRow').click(function () {
var row = $(' <tbody id=\'appendrow\' class=\'appendrow\'><tr><td> <input type=\'text\' required class=\'form-control\' name=\'sku[]\' onclick=\'filtersku(this,' + counter + ');\'> <input type=\'hidden\' id=\'product_id' + counter + '\' name=\'product_id[]\'/></td> <td> <input type=\'text\' readonly data-field=\'vendorsku\' id=\'vendor_sku' + counter + '\' name=\'vendorsku[]\'class=\'form-control\'></td> <td><input class=\'form-control\' data-field=\'quantity\' type=\'text\' required id=units_ordered' + counter + '\' name=\'units_ordered[]\' /></td> <td><input class=\'form-control\' type=\'text\' data-field=\'price\' required name=\'vendor_unit_price[]\' id=\'vendor_price' + counter + '\'></td> <td><input name=\'discount_percent[]\' data-field=\'discount\' class=\'form-control\' ><input type=\'hidden\' data-field=\'discountnumber\' class=\'form-control\' id=\'discountnumber\' ></td><td><input type=\'text\' readonly data-field=\'tax\' id=\'tax_id' + counter + '\' class=\'form-control\' name=\'tax_id[]\' /></td><td> Rs. <span data-field=\'taxPrice\' id=\'taxPrice' + counter + '\' >0</span><input type=\'hidden\' data-field=\'taxPriceInput\' id=\'taxPriceInput' + counter + '\' class=\'taxPrice\' value = \'0\'/> </td> <td><input type=\'text\' class=\'form-control\'data-field=\'total\' name=\'subtotal[]\'/><input type=\'hidden\' data-field=\'totalbeforetax\' class=\'form-control\' id=\'subtotalbeforetax\' /></td><td><button type=\'button\' class=\'btn btn-danger\' name=\'delete[]\' onclick=\'javascript:deletefun(this);\'><i class=\'fa fa-trash\' aria-hidden=\'true\'></i></button></td></tr></tbody>');
$('#example').append(row);
counter++;
});
});
});
function validation() {
var ordered = parseInt(document.getElementById('units_ordered0').value);
var inventory = parseInt(document.getElementById('inventory0').value);
if (inventory == -1) {
return true;
}
else {
if (ordered <= inventory) {
return true;
}
else {
document.getElementById('error').innerHTML = ('Ordered units of a product cannot be greater than the number of products present in inventory whose value is ' + inventory).fontcolor('red');
return false;
}
}
}
Please note the correct structure of the HTML5 Table. Here is a clean HTML5 Table structure:
<table>
<caption>Table Caption</caption>
<colgroup>
<col>
<col>
</colgroup>
<thead>
<tr>
<th>Header Row 1</th>
<th>Header Row 2</th>
<th>Header Row 3</th>
</tr>
</thead>
<tfoot>
<tr>
<td>Footer Row 1</td>
<td>Footer Row 2</td>
<td>Footer Row 3</td>
</tr>
</tfoot>
<tbody>
<tr>
<td>Body Row 1</td>
<td>Body Row 2</td>
<td>Body Row 3</td>
</tr>
</tbody>
</table>
And about your question:
var counter = 1;
document.getElementById( 'addRow' ).addEventListener( 'click', function ( e ) {
var table = document.getElementById( 'myTable' ),
row = table.insertRow( counter ),
cell1 = row.insertCell( 0 ),
cell2 = row.insertCell( 1 );
cell1.innerHTML = '<input type="text" data-field="quantity" class="form-control" name="units_ordered[]" id="units_ordered' + counter + '" required/>';
cell2.innerHTML = '<input type="text" data-field="inventory" class="form-control" name="inventory" id="inventory' + counter + '"/>';
counter++;
e.preventDefault()
} )
document.getElementById( 'validate' ).addEventListener( 'click', function ( e ) {
validation();
e.preventDefault()
} )
function validation() {
var ordered = document.querySelectorAll( 'input[id^="units_ordered"]' ),
inventory = document.querySelectorAll( 'input[id^="inventory"]' );
document.getElementById( 'error' ).innerHTML = ''
ordered.forEach( function ( item, index ) {
var ordered_val = Number( item.value ) || 0,
inventory_val = Number( inventory[ index ].value ) || 0
if ( inventory_val == -1 ) {
return true
} else {
if ( ordered_val <= inventory_val ) {
return true
} else {
document.getElementById( 'error' ).innerHTML += 'Row ' + +( index + 1 ) + ': Ordered units of a product cannot be greater than the number of products present in inventory whose value is ' + inventory_val + '<br/>';
return false
}
}
} )
}
table {
font-family: arial, sans-serif;
border-collapse: collapse;
width: 300px
}
td, th {
border: 1px solid #86af49;
text-align: left;
padding: 0
}
th {
padding: 5px;
color: #fff;
background-color: #86af49
}
input[type="text"] {
box-sizing: border-box;
width: 100%;
border: 0;
outline: none
}
#error {
color: red;
font-size: .75em
}
<p>
<button type="button" id="addRow">Add Row</button>
<button type="button" id="validate">Validation</button>
</p>
<table id="myTable">
<thead>
<tr>
<th>Ordered</th>
<th>Inventory</th>
</tr>
</thead>
<tbody>
<tr>
<td>
<input type="text" data-field="quantity" class="form-control" name="units_ordered[]" id="units_ordered0" required/>
</td>
<td>
<input type="text" data-field="inventory" class="form-control" name="inventory" id="inventory0"/>
</td>
</tr>
</tbody>
</table>
<p id="error"></p>
I have a form which displays rows from a database table and an update button with each row.
I need to add a blank row on a button click (ADD ENTRY) exactly like the ones above in the form and a save button with this row, like above (update button), using JavaScript.
The following is the HTML and the JS I'm using. This is how my page looks like:
<?php
include('adodb/adodb.inc.php');
echo '<h1>Mxpresso Revenue Management Solution</h1>';
echo '<img src="http://mxpresso.com/images/logo.png" alt="mxpresso logo" style="width:171px;height:108px;">';
echo '<h2>See existing records</h2>';
$db=NewADOConnection('mysql');$db->Connect("127.0.0.1", "vc", "abc", "vc");
$sql="select * from rev";
$result = $db->Execute($sql);
if ($result === false) die("failed2");
$records=array();
$count=$result->RecordCount();
echo "Total Records Found :".$count."<br>";
if($count > 0) {
echo '<style>
input{
outline:none;
border: none;
}
</style>
<table id="datatable" class="form" border="1" width="50%">
<col width="10%">
<col width="10%">
<col width="10%">
<col width="10%">
<col width="10%">
<tbody>
<tr>
<th><h4>OfferID</h4></th>
<th><h4>AffID</h4></th>
<th><h4>Deduction</h4></th>
<th><h4>Status</h4></th>
<th><h4>Update Entry</h4></th>
</tr>';
while (!$result->EOF){
$offerId=$result->fields[0];
$affId=$result->fields[1];
$status=$result->fields[2];
$deduction=$result->fields[3];
echo'<form target="_blank" action ="updatecopy.php" id="myform" method="get">
<tr>
<td><input type="text" name="update_for_offerid" value='.$offerId.'></td>
<td><input type="text" name="update_for_affid" value='.$affId.'></td>
<td><input type="text" name="deduct" value='.$deduction.'></td>
<td><input type="text" name="status" value='.$status.' ></td>
<td><input type="submit" size="23" value="Update Entry" style="color : Black;width:165px"></td>
</tr>
</form>';
$rec=array("offerId"=>$offerId,"affiliate_id"=>$affId,"status"=>$status, "deduction"=>$deduction);
array_push($records,$rec);
$result->MoveNext();
}
}
echo '</tbody>
</table>
<div id="dynamicinput1">
</div>
<form><input type="button" value="Add Entry" style="font-family: sans-serif; font-size: 15px; color : Black;" onClick="addInput(\'dynamicinput1\');">
</form>
<script language="Javascript" type="text/javascript">
var counter = 1;
var limit = 10;
function addInput(divName){
if (counter == limit) {
alert("You have reached the limit of adding " + counter + " inputs");
}
else {
var fool = document.createElement(\'form\');
var newtable = document.createElement(\'Table\');
var tr = document.createElement(\'tr\');
newtable.style.border = "1px solid black";
tr.style.width="10px";
var td1 = document.createElement(\'td\');
td1.innerHTML = "<br><input type=\'text\' name=\'offerId\'>";
td1.style.border = "1px solid black";
var td2 = document.createElement(\'td\');
td2.innerHTML ="<br><input type=\'text\' name=\'affId\'>";
td2.style.border = "1px solid black";
var td3 = document.createElement(\'td\');
td3.innerHTML ="<br><input type=\'text\' name=\'status\'>";
td3.style.border = "1px solid black";
var td4 = document.createElement(\'td\');
td4.innerHTML ="<br><input type=\'text\' name=\'deduct\'>";
td4.style.border = "1px solid black";
tr.appendChild(td1);
tr.appendChild(td2);
tr.appendChild(td3);
tr.appendChild(td4);
newtable.appendChild(tr);
fool.appendChild(newtable);
fool.action = "insertcopy.php"
var save = document.createElement(\'input\');
save.type = "submit";
save.value = "Save Entry";
fool.appendChild(save);
tr.appendchild(save);
document.getElementById(divName).appendChild(fool);
counter++;
}
}
</script>';
?>
It may help you.
$(document).ready(function() {
$('a').click(function() {
$('#myTable tbody').append('<tr class="child"><td><input type="text"></td><td><input type="text"></td><td<input type="text"></td><td><input type="text"></td><td><input type="text"></td><td>submit</td></tr>');
});
});
input{
width:40px;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.0/jquery.min.js"></script>
add new
<table id="myTable">
<thead>
<tr>
<td>offerID</td>
<td>affid</td>
<td>deduction</td>
<td>status</td>
<td>update entry</td>
</tr>
</thead>
<tbody>
<tr>
<td>123</td>
<td>231</td>
<td>12</td>
<td>654</td>
<td>update</td>
</tr>
<tr>
<td>123</td>
<td>231</td>
<td>12</td>
<td>654</td>
<td>update</td>
</tr>
<tr>
<td>123</td>
<td>231</td>
<td>12</td>
<td>654</td>
<td>update</td>
</tr>
</tbody>
</table>
Write an sql query to add data to the table. Then you execute your sql query
Example:
$SQL= "INSERT INTO table_name (column_name1, column_name2...) VALUES ('$val1', '$val2')";
$exeSQL=mysql_query($SQL) or die (mysql_error());
I am trying to dynamically add rows to a table to take orders and have created a javascript function for it.
function addnewrow()
{
var lastid = $("#table tr:last").attr("id");
var newid=lastid+1;
var newcolumn = document.createElement("tr");
newcolumn.id=newid;
newcolumn.innerHTML = "<td id='no"+newid+"'><a class='cut'>-</a>"+newid+"</td>"+
"<td>"+
"<ajaxToolkit:ComboBox ID='prod"+newid+"' runat='server' DataSourceID='SqlDataSource2' DataTextField='pname' DataValueField='pid' MaxLength='0' style='display: inline;'></ajaxToolkit:ComboBox>" +
"</td>"+
"<td><input type='number' required='required' min='1' name='quantity" + newid + "' /></td>" +
"<td id='price" + newid + "'></td>" +
"<td id='amount" + newid + "'></td>";
document.getElementById("table").appendChild(newcolumn);
}
I am doing this to get the values of all the elements in the code behind file to put them in database.
but due to this i get an error in the aspx.designer.cs page saying semicolon expected
protected global::AjaxControlToolkit.ComboBox prod" + newid + ";
ASP.NET Code
<table class="Grid" id="table">
<tr>
<td colspan="5">Enter Order Details</td>
</tr>
<tr>
<th>Sr No.</th>
<th>Product</th>
<th>Quantity</th>
<th>Price</th>
<th>Amount</th>
</tr>
<tr id="1">
<td><a class="cut">-</a>1</td>
<td>
<ajaxToolkit:ComboBox ID="prod1" runat="server" DataSourceID="SqlDataSource2" DataTextField="pname" DataValueField="pid" MaxLength="0" style="display: inline;"></ajaxToolkit:ComboBox>
<asp:SqlDataSource ID="SqlDataSource2" runat="server" ConnectionString="<%$ ConnectionStrings:micoConnectionString %>" SelectCommand="SELECT [pid], [pname] FROM [Products]"></asp:SqlDataSource>
</td>
<td><input type="number" required="required" min="1" name="quantity1" /></td>
<td id="price1"></td>
<td id="amount1"></td>
</tr>
</table>
<a class="add" onclick="addnewrow()" href="#">+</a>
Check this
$("#btnAddSchedule").click(function () {
var trs = $("[id^=trSchedules]");
var numberofrows = trs.length;
var newtr = $('#' + trs[0].id).clone();
$(newtr).attr('id', $(newtr).attr('id').replace(/\d+/, numberofrows));
newtr.find("input,select,img").each(function () {
$(this).attr('id', $(this).attr('id').replace(/\d+/, numberofrows));
$(this).attr('name', $(this).attr('name').replace(/\d+/, numberofrows));
if ($(this).attr('type') != "hidden") {
$(this).val('');
}
else if ($(this).attr('id').indexOf('DataExportQueueID') == -1) {
$(this).val('');
}
if ($(this).attr("type") == "checkbox") {
$(this).removeAttr("checked");
$(this).parent().html($(this).parent().html().replace(/\d+/g, numberofrows));
}
if ($(this).attr("type") == "button") {
$(this).attr("onclick", "deleteSchedule(this,0);");
}
});
$('#' + trs[numberofrows - 1].id).after(newtr);
CrossCheckScheduleRows();
});
function CrossCheckScheduleRows() {
$('[id^=trSchedules]').each(function () {
var row = $(this);
var index = row[0].rowIndex - 2;
row.attr('id', row.attr('id').replace(/\d+/, index));
row.find("input,select,img").each(function () {
$(this).attr('id', $(this).attr('id').replace(/\d+/, index)).attr('name', $(this).attr('name').replace(/\d+/, index));
});
});
}
I use this for the same purpose, maybe it will help you
I have an HTML table with a header and a footer:
<table id="myTable">
<thead>
<tr>
<th>My Header</th>
</tr>
</thead>
<tbody>
<tr>
<td>aaaaa</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>My footer</td>
</tr>
<tfoot>
</table>
I am trying to add a row in tbody with the following:
myTable.insertRow(myTable.rows.length - 1);
but the row is added in the tfoot section.
How do I insert tbody?
If you want to add a row into the tbody, get a reference to it and call its insertRow method.
var tbodyRef = document.getElementById('myTable').getElementsByTagName('tbody')[0];
// Insert a row at the end of table
var newRow = tbodyRef.insertRow();
// Insert a cell at the end of the row
var newCell = newRow.insertCell();
// Append a text node to the cell
var newText = document.createTextNode('new row');
newCell.appendChild(newText);
<table id="myTable">
<thead>
<tr>
<th>My Header</th>
</tr>
</thead>
<tbody>
<tr>
<td>initial row</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>My Footer</td>
</tr>
</tfoot>
</table>
(old demo on JSFiddle)
You can try the following snippet using jQuery:
$(table).find('tbody').append("<tr><td>aaaa</td></tr>");
Basic approach:
This should add HTML-formatted content and show the newly added row.
var myHtmlContent = "<h3>hello</h3>"
var tableRef = document.getElementById('myTable').getElementsByTagName('tbody')[0];
var newRow = tableRef.insertRow(tableRef.rows.length);
newRow.innerHTML = myHtmlContent;
I think this script is what exactly you need
var t = document.getElementById('myTable');
var r =document.createElement('TR');
t.tBodies[0].appendChild(r)
You're close. Just add the row to the tbody instead of table:
myTbody.insertRow();
Just get a reference to tBody (myTbody) before use. Notice that you don't need to pass the last position in a table; it's automatically positioned at the end when omitting argument.
A live demo is at jsFiddle.
Add rows:
<html>
<script>
function addRow() {
var table = document.getElementById('myTable');
//var row = document.getElementById("myTable");
var x = table.insertRow(0);
var e = table.rows.length-1;
var l = table.rows[e].cells.length;
//x.innerHTML = " ";
for (var c=0, m=l; c < m; c++) {
table.rows[0].insertCell(c);
table.rows[0].cells[c].innerHTML = " ";
}
}
function addColumn() {
var table = document.getElementById('myTable');
for (var r = 0, n = table.rows.length; r < n; r++) {
table.rows[r].insertCell(0);
table.rows[r].cells[0].innerHTML = " ";
}
}
function deleteRow() {
document.getElementById("myTable").deleteRow(0);
}
function deleteColumn() {
// var row = document.getElementById("myRow");
var table = document.getElementById('myTable');
for (var r = 0, n = table.rows.length; r < n; r++) {
table.rows[r].deleteCell(0); // var table handle
}
}
</script>
<body>
<input type="button" value="row +" onClick="addRow()" border=0 style='cursor:hand'>
<input type="button" value="row -" onClick='deleteRow()' border=0 style='cursor:hand'>
<input type="button" value="column +" onClick="addColumn()" border=0 style='cursor:hand'>
<input type="button" value="column -" onClick='deleteColumn()' border=0 style='cursor:hand'>
<table id='myTable' border=1 cellpadding=0 cellspacing=0>
<tr id='myRow'>
<td> </td>
<td> </td>
<td> </td>
</tr>
<tr>
<td> </td>
<td> </td>
<td> </td>
</tr>
</table>
</body>
</html>
And cells.
let myTable = document.getElementById('myTable').getElementsByTagName('tbody')[0];
let row = myTable.insertRow();
let cell1 = row.insertCell(0);
let cell2 = row.insertCell(1);
let cell3 = row.insertCell(2);
cell1.innerHTML = 1;
cell2.innerHTML = 'JAHID';
cell3.innerHTML = 23;
row = myTable.insertRow();
cell1 = row.insertCell(0);
cell2 = row.insertCell(1);
cell3 = row.insertCell(2);
cell1.innerHTML = 2;
cell2.innerHTML = 'HOSSAIIN';
cell3.innerHTML = 50;
table {
border-collapse: collapse;
}
td, th {
border: 1px solid #000;
padding: 10px;
}
<table id="myTable">
<thead>
<tr>
<th>ID</th>
<th>NAME</th>
<th>AGE</th>
</tr>
</thead>
<tbody></tbody>
</table>
Add Column, Add Row, Delete Column, Delete Row. Simplest way
function addColumn(myTable) {
var table = document.getElementById(myTable);
var row = table.getElementsByTagName('tr');
for(i=0;i<row.length;i++){
row[i].innerHTML = row[i].innerHTML + '<td></td>';
}
}
function deleterow(tblId)
{
var table = document.getElementById(tblId);
var row = table.getElementsByTagName('tr');
if(row.length!='1'){
row[row.length - 1].outerHTML='';
}
}
function deleteColumn(tblId)
{
var allRows = document.getElementById(tblId).rows;
for (var i=0; i<allRows.length; i++) {
if (allRows[i].cells.length > 1) {
allRows[i].deleteCell(-1);
}
}
}
function myFunction(myTable) {
var table = document.getElementById(myTable);
var row = table.getElementsByTagName('tr');
var row = row[row.length-1].outerHTML;
table.innerHTML = table.innerHTML + row;
var row = table.getElementsByTagName('tr');
var row = row[row.length-1].getElementsByTagName('td');
for(i=0;i<row.length;i++){
row[i].innerHTML = '';
}
}
table, td {
border: 1px solid black;
border-collapse:collapse;
}
td {
cursor:text;
padding:10px;
}
td:empty:after{
content:"Type here...";
color:#cccccc;
}
<!DOCTYPE html>
<html>
<head>
</head>
<body>
<form>
<p>
<input type="button" value="+Column" onclick="addColumn('tblSample')">
<input type="button" value="-Column" onclick="deleteColumn('tblSample')">
<input type="button" value="+Row" onclick="myFunction('tblSample')">
<input type="button" value="-Row" onclick="deleterow('tblSample')">
</p>
<table id="tblSample" contenteditable><tr><td></td></tr></table>
</form>
</body>
</html>
You can also use querySelector to select the tbody, then insert a new row at the end of it.
Use append to insert Node or DOMString objects to a new cell, which will then be inserted into the new row.
var myTbody = document.querySelector("#myTable>tbody");
var newRow = myTbody.insertRow();
newRow.insertCell().append("New data");
<table id="myTable">
<thead>
<tr>
<th>My Header</th>
</tr>
</thead>
<tbody>
<tr>
<td>Data</td>
</tr>
</tbody>
<tfoot>
<tr>
<td>My footer</td>
</tr>
</tfoot>
</table>
I have tried this, and this is working for me:
var table = document.getElementById("myTable");
var row = table.insertRow(myTable.rows.length-2);
var cell1 = row.insertCell(0);
You can use the following example:
<table id="purches">
<thead>
<tr>
<th>ID</th>
<th>Transaction Date</th>
<th>Category</th>
<th>Transaction Amount</th>
<th>Offer</th>
</tr>
</thead>
<!-- <tr th:each="person: ${list}" >
<td><li th:each="person: ${list}" th:text="|${person.description}|"></li></td>
<td><li th:each="person: ${list}" th:text="|${person.price}|"></li></td>
<td><li th:each="person: ${list}" th:text="|${person.available}|"></li></td>
<td><li th:each="person: ${list}" th:text="|${person.from}|"></li></td>
</tr>
-->
<tbody id="feedback">
</tbody>
</table>
JavaScript file:
$.ajax({
type: "POST",
contentType: "application/json",
url: "/search",
data: JSON.stringify(search),
dataType: 'json',
cache: false,
timeout: 600000,
success: function (data) {
// var json = "<h4>Ajax Response</h4><pre>" + JSON.stringify(data, null, 4) + "</pre>";
// $('#feedback').html(json);
//
console.log("SUCCESS: ", data);
//$("#btn-search").prop("disabled", false);
for (var i = 0; i < data.length; i++) {
//$("#feedback").append('<tr><td>' + data[i].accountNumber + '</td><td>' + data[i].category + '</td><td>' + data[i].ssn + '</td></tr>');
$('#feedback').append('<tr><td>' + data[i].accountNumber + '</td><td>' + data[i].category + '</td><td>' + data[i].ssn + '</td><td>' + data[i].ssn + '</td><td>' + data[i].ssn + '</td></tr>');
alert(data[i].accountNumber)
}
},
error: function (e) {
var json = "<h4>Ajax Response</h4><pre>" + e.responseText + "</pre>";
$('#feedback').html(json);
console.log("ERROR: ", e);
$("#btn-search").prop("disabled", false);
}
});
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8" />
<link rel="stylesheet" type="text/css" href="css/style.css" />
<title>Expense Tracker</title>
</head>
<body>
<h1>Expense Tracker</h1>
<div id="myDiv">
<label for="name">Name:</label>
<input
type="text"
name="myInput"
id="myInput"
placeholder="Name of expense"
size="50"
/><br /><br />
<label for="date">Date:</label>
<input type="date" id="myDate" name="myDate" />
<label for="amount">Amount:</label>
<input
type="text"
name="myAmount"
id="myAmount"
placeholder="Dollar amount ($)"
/><br /><br />
<span onclick="addRow()" class="addBtn">Add Expense</span>
</div>
<br />
<input type="button" value="Add Rows" onclick="addRows()" />
<!-- Optional position -->
<table id="myTable">
<tr>
<th>Name</th>
<th>Date</th>
<th>Amount</th>
<th>Delete</th>
</tr>
<tr>
<td>McDonald's</td>
<td>6/22/2017</td>
<td>$12.00</td>
<td>
<input type="button" value="Delete" onclick="deleteRow(this)" />
</td>
</tr>
</table>
<script>
function deleteRow(r) {
var i = r.parentNode.parentNode.rowIndex;
document.getElementById("myTable").deleteRow(i);
}
function addRows() {
console.log("add rows");
document.getElementById("myTable").innerHTML += `<tr>
<td>McDonald's</td>
<td>6/22/2017</td>
<td>$12.00</td>
<td>
<input type="button" value="Delete" onclick="deleteRow(this)" />
</td>
</tr>`;
}
</script>
</body>
</html>
$("#myTable tbody").append(tablerow);