How to only delete last row of table? - javascript

I have this JS code to add and remove table rows when user clicks a button. Adding rows works like a dream. My issue is the user clicks the Delete button, all but the first row is deleted. I only want the last row to be deleted, say if they add to many rows.
EDIT
I have tryed this
function deleteRow(tableID) {
var table = document.getElementById(tableID);
if(table.rows.length <= 1) { // limit the user from removing all the fields
alert("Cannot Remove all the fields.");
break;
}
table.deleteRow(table.rows.length -1);
}
But when i take the loop out the Add button no longer works...
<script>
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
if(rowCount < 50){ // limit the user from creating fields more than your limits
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
for(var i=0; i <colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[0].cells[i].innerHTML;
}
}else{
alert("Maximum Unit limit is 5");
}
}
function deleteRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for(var i=0; i<rowCount; i++) {
var row = table.rows[i];
if(rowCount <= 1) { // limit the user from removing all the fields
alert("Cannot Remove all the fields.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
</script>

To delete the last row of the table you can use this.
function deleteRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
table.deleteRow(rowCount -1);
}

You dont need a for loop, this code will work:
function deleteRow(tableID) {
var table = document.getElementById(tableID);
if(table.rows.length <= 1) { // limit the user from removing all the fields
alert("Cannot Remove all the fields.");
break;
}
table.deleteRow(table.rows.length -1);
}

Related

How to count the number of visible rows in html table that contains a specific word

so i have a csv parser and in html i want to know the the number of occurrences of a specified word in visible rows after searching for something
here is my code:
function no(){
var input, filter, table, tr, td, cell, i, j;
filter = document.getElementById("searchInput").value.toLowerCase();
table = document.getElementById("table1");
tr = table.getElementsByTagName("tr");
for (i = 1; i < tr.length; i++) {
tr[i].style.display = "none";
const tdArray = tr[i].getElementsByTagName("td");
for (var j = 0; j < tdArray.length; j++) {
const cellValue = tdArray[j];
if (cellValue && cellValue.innerHTML.toLowerCase().indexOf(filter) > -1) {
tr[i].style.display = "";
break;
}
//var update = $('table tr:contains(Update)').length;
}
}
var update = $('table tr:contains(Update)').length;
update = "Update Operations: " + update
document.getElementById("update").innerHTML = update;
var HardDelete= $('table tr:contains(HardDelete)').length;
HardDelete = "HardDelete Operations: " + HardDelete
document.getElementById("HardDelete").innerHTML = HardDelete;
var SoftDelete = $('table tr:contains(SoftDelete)').length;
SoftDelete = "SoftDelete Operations: " + SoftDelete
document.getElementById("SoftDelete").innerHTML = SoftDelete;
var Create = $('table tr:contains(Create)').length;
Create = "Create Operations: " + Create
document.getElementById("create").innerHTML = Create;
}
</script>
i wrote this var Create = $('table tr:contains(Create)').length; ) like this var Create = $('table tr:contains(Create) tr:visible').length; but it wont work.
but i dont know how to write it properly can you please help?

How to clear the data of new row?

I am adding new rows like this:
var table = document.getElementById('dataTable');
var rowCount = table.rows.length;
var row = table.insertRow(2);
var colCount = table.rows[3].cells.length;
for (var i = 0; i < colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = able.rows[3].cells[i].innerHTML;
}
I don't want to loose input field data when refresh is done so, I use php session like these:
isset($_POST['details'])?$_SESSION['details'] = $_POST['details']:$_SESSION['details']="";
when I refresh and return same page session hold the previous data.
My problem is when i click add row button it generates same(previously inserted) data in new row also.
So I want to ask how to clear the data in new row. I think I need to have some code here:
for (var i = 0; i < colCount; i++) {
//need some code here to clear the field in newly created fields
var newcell = row.insertCell(i);
newcell.innerHTML = able.rows[3].cells[i].innerHTML;
}

javascript dyanmic table add / delete row

I am trying to build a form for creating a list for image deployment.
I am able to create a dynamic table on form load and also collect the data for each value, but can seem to get the Add and Delete working.
My Question:
What must I do(or change) in my code to get the ADD and Delete options working and to export the table data in CSV format.
Please could someone help and/or guide me as I am getting so lost and really would like a working example .. there is so much on the net it's over-whelming
Newest place I visited is Mozilla DOM help pages what's confusing is how to load your own variables into the table
For reference I used stackoverflow and plenty google and finally this site
Here is my code:
<div id="metric_results">
Enter Target Name:
<input type="text" name="textbox1" id="textbox1" VALUE="win2k8"/>
<br>
<input type="button" id="create" value="Click here" onclick="Javascript:addTable()">
<input type="button" id="create" value="Add Row" onclick="Javascript:addRow()">
<input type="button" id="create" value="Delete Row" onclick="Javascript:deleteRow()">
</div>
<SCRIPT LANGUAGE="JavaScript">
window.onload =addTable;//loads table on window loading
function addTable() {
var myTableDiv = document.getElementById("metric_results")
var table = document.createElement('TABLE')
var tableBody = document.createElement('TBODY')
var imageName = textbox1.value
table.border = '1'
table.appendChild(tableBody);
var heading = new Array();
heading[0] = "imageName"
heading[1] = "acceptAllEula"
heading[2] = "noSSLverify"
heading[3] = "noVerification"
heading[4] = "TargetImagelocation"
heading[5] = "Username"
heading[6] = "Password"
heading[7] = "Target IP"
var imageInfo = new Array()
imageInfo[0] = new Array(imageName, "acceptAllEula", "noSSLverify", "noVerification", "testLocation", "user", "pass", "192.168.1.151")
imageInfo[1] = new Array("win2008", "acceptAllEula", "noSSLverify", "noVerification", "testLocation", "user", "pass", "192.168.1.151")
//TABLE COLUMNS
var tr = document.createElement('TR');
tableBody.appendChild(tr);
for (i = 0; i < heading.length; i++) {
var th = document.createElement('TH')
th.width = '75';
th.appendChild(document.createTextNode(heading[i]));
tr.appendChild(th);
}
//TABLE ROWS
for (i = 0; i < imageInfo.length; i++) {
var tr = document.createElement('TR');
for (j = 0; j < imageInfo[i].length; j++) {
var td = document.createElement('TD')
td.appendChild(document.createTextNode(imageInfo[i][j]));
tr.appendChild(td)
}
tableBody.appendChild(tr);
}
myTableDiv.appendChild(table)
}
function addRow() {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[0].cells.length;
var cell1 = row.insertCell(0);
var element1 = document.createElement("input");
element1.type = "checkbox";
element1.name="chkbox[]";
cell1.appendChild(element1);
var cell2 = row.insertCell(1);
cell2.innerHTML = rowCount + 1;
var cell3 = row.insertCell(2);
var element2 = document.createElement("input");
element2.type = "text";
element2.name = "txtbox[]";
cell3.appendChild(element2);
}
function deleteRow(tableID) {
try {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for(var i=0; i<rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if(null != chkbox && true == chkbox.checked) {
table.deleteRow(i);
rowCount--;
i--;
}
}
function deleteRow(tableID) {
try {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for(var i=0; i<rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if(null != chkbox && true == chkbox.checked) {
table.deleteRow(i);
rowCount--;
i--;
}
}
}catch(e) {
alert(e);
}
</SCRIPT>
You're not setting any id to the table you're creating onload - so when you later come to call getElementById() inside addRow it cannot be found (and you're using a variable which does not exist - tableID!)
My suggestion is to take an id as a parameter to addTable, and set that as the id of the dynamically generated table:
function addTable(id) {
var myTableDiv = document.getElementById("metric_results")
var table = document.createElement('TABLE')
table.id = id;
....
onload, pass somethig sensible - default perhaps:
window.onload = function(){
addTable("default");
}
And either pass this in when adding a row, or use the default provided above:
function addRow() {
var table = document.getElementById("default");
....
or
function addRow(id) {
var table = document.getElementById(id);
Updated fiddle: https://jsfiddle.net/egtu5kay/5/
Left as an exercise for you: Correctly formatting the new row as you wish.

Dynamic HTML row - add id on TR

How to add an ID (value 1, 2, 3, etc.) on each new
I have now so that my script creates a new row, but would need an ID to each
FIDDLE
CODE:
function deleteRow(tableID) {
try {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for(var i=0; i<rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if(null != chkbox && true == chkbox.checked) {
if(rowCount <= 1) {
alert("Cant delete all rows");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}catch(e) {
alert(e);
}
}
So, simply add id when you create new line. Removed IDs aren't used again, ID is still unique.
var row_id = 1;
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
row.id = 'id' + row_id; // ID is 'id#' because valid ID can't start with a number
row_id++;
...
http://jsfiddle.net/pkz1vszu/2/
You can use jQuery to make it easier:
<head>
<script src="js/jquery-1.11.1.min.js"></script>
</head>
<body>
<script>
$("#create_button").click(function(){
$("<tr>").attr({"id":"id_"+number}).appendTo("#table");
]);
</script>
...
...
</body>

Delete the row you click on (Javascript dynamic table)

I want to delete a row from a table, I am using Javascript.
I am dynamically creating table rows and in the last cell I have delete button so how to make it delete the row?
var newData4 = document.createElement('td');
var delButton = document.createElement('input');
delButton.setAttribute('type', 'button');
delButton.setAttribute('name', 'deleteButton');
delButton.setAttribute('value', 'Delete');
newData4.appendChild(delButton);
newRow.appendChild(newData4);
this is the function for creating my table rows
function addItem()
{
document.getElementById('add').onclick=function()
{
var myTable = document.getElementById('tbody');
var newRow = document.createElement('tr');
//var element1 = document.createElement("input");
//element1.type = "checkbox";
//newRow.appendChild(element1);
var newData1 = document.createElement('td');
newData1.innerHTML = document.getElementById('desc').value;
var newData2 = document.createElement('td');
newData2.innerHTML = document.getElementById('taskPriority').value;
var newData3 = document.createElement('td');
newData3.innerHTML = document.getElementById('taskDue').value;
myTable.appendChild(newRow);
newRow.appendChild(newData1);
newRow.appendChild(newData2);
newRow.appendChild(newData3);
var newData4 = document.createElement('td');
var delButton = document.createElement('input');
delButton.setAttribute('type', 'button');
delButton.setAttribute('name', 'deleteButton');
delButton.setAttribute('value', 'Delete');
newData4.appendChild(delButton);
newRow.appendChild(newData4);
}
}
function SomeDeleteRowFunction(btndel) {
if (typeof(btndel) == "object") {
$(btndel).closest("tr").remove();
} else {
return false;
}
}
try this code here is fiddle
alternatively try
//delete the table row
$(document).on('click', '#del', function(){
$(this).parents('tr').remove();
});
}); //del is the id of the delete block
one pure javascript approach
function deleteRowUI(btndel) {
var table=document.getElementById('filterTableBody');
if (typeof(btndel) == "object") {
p=btndel.parentNode.parentNode;
p.parentNode.removeChild(p);
var oTable = document.getElementById('filterTableBody');
//gets rows of table
var rowLength = oTable.rows.length;
for (var i = 1; i < rowLength; i++){
var oCells = oTable.rows.item(i).cells;
//gets cells of current row
var cellLength = oCells.length-1;
for(var j = 0; j < cellLength; j++){
oCells.item(j).innerHTML = "";
break;
}
break;
}
} else {
return false;
}
}
if you want to temporary hidden it you can do:
this.parentNode.style.display='none';
in mind that the exclusion button is in a td.
But if you want to really delete it from the html and the database:
you need to make the same as above and a extra call to a function of php/plsqlwathever to delete from de db, i recommend using ajax to call it.
http://www.w3schools.com/ajax/default.asp
uses jQuery remove method to do it.
By the id attribute :
$("#id here").remove();
By the class attribute :
$(".class name here").remove();
I hope I've helped a little...

Categories

Resources