Dynamicaly delet the table row using check box and javascript - javascript

How can we Dynamically delete the html table rows using javascript.
We have a check box on each row. While clicking the remove button with the check box selected the row would be deleted. Such as
document.getElementById(j).innerHTML = '';

Removing an element is best done with DOM node functions like removeChild, rather than innerHTML-hacking. eg.:
function removeAllRowsContainingCheckedCheckbox(table) {
for (var rowi= table.rows.length; rowi-->0;) {
var row= table.rows[rowi];
var inputs= row.getElementsByTagName('input');
for (var inputi= inputs.length; inputi-->0;) {
var input= inputs[inputi];
if (input.type==='checkbox' && input.checked) {
row.parentNode.removeChild(row);
break;
}
}
}
}

Here's a small mockup on how this could be done:
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<title>Mockup</title>
<script type="text/javascript">
function killRow(src) {
var dRow = src.parentElement.parentElement;
document.all("table").deleteRow(dRow.rowIndex);
}
</script>
</head>
<body>
<form action="something.html">
<table id="table">
<tr>
<td><input type='checkbox' onclick='killRow(this);'>Click me!</td>
<td>Demodata 1</td>
</tr>
<tr>
<td><input type='checkbox' onclick='killRow(this);'>Click me!</td>
<td>Demodata 2</td>
</tr>
</table>
</form>
</body>
</html>
Key in this is a JScript-function which then can be used from any row in there. It might even be more generalized. When clicking on the checkboxes the function is called.
I'd rather not use innerHTML on this, I'd prefer DOM nodes (here parentElement).

Here is a function that performs the required action of deleting rows by checking the value of checkbox. Call this function in the onclick event of the delete button(Comments included). Hope this helps :)
function removeSampleRow(id) {
/***We get the table object based on given id ***/
var objTable = document.getElementById(id);
/*** Get the current row length ***/
var iRow = objTable.rows.length;
/*** Initial row counter ***/
var counter = 0;
/*** Performing a loop inside the table ***/
if (objTable.rows.length > 1) {
for (var i = 0; i < objTable.rows.length; i++) {
/*** Get checkbox object ***/
var chk = objTable.rows[i].cells[0].childNodes[0];
if (chk.checked) {
/*** if checked we del ***/
objTable.deleteRow(i);
iRow--;
i--;
counter = counter + 1;
}
}
/*** Alert user if there is now row is selected to be deleted ***/
if (counter == 0) {
alert("Please select the row that you want to delete.");
}
}else{
/*** Alert user if there are no rows being added ***/
alert("There are no rows being added");
}
}

Related

Dynamically add and remove rows of cascading dropdown lists?

So I'm trying to make a form where the user can dynamically add and remove rows containing cascading dropdowns as a class picker.
So far I've been able to make everything work except for the remove selected classes function.
I've tried a couple different deleteRow functions but can't seem to make it work.
My most recent attempt is by using the checkbox input but I'm open to any other solutions.
Thanks
<!DOCTYPE html>
<html>
<head>
<title>Semesters Planned</title>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<script>
$(function() {
$('#selectCategory').change(function() {getSelectedItem(this, null); });
$('#button').click(function()
{addRow('dataTable'); });
var classes = {//can probably use external text files for these later on
"Core": ["UNI101", "ENG101"],
"Major": ["CSC101", "CSC180"],
"Elective": ["ART101", "PSY101"]
};
var keys = Object.keys(classes);
var category_dropdown = document.getElementById("selectCategory");
var getSelectedItem = function(element, row) {
var e = element;
var selectedCategory = e.options[e.selectedIndex].value;
var sub_category_dropdown = (row != null ? row.getElementsByTagName("select")[1] : document.getElementById("selectSubCategory"));
sub_category_dropdown.options.length = 0;
for (var i = 0; i < classes[selectedCategory].length; i++) {
sub_category_dropdown[sub_category_dropdown.length] = new Option(classes[selectedCategory][i], classes[selectedCategory][i]);
}
};
var addRow = function(tableID)
{
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
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;
newcell.childNodes[0].selectedIndex = 0;
}
var selects = row.getElementsByTagName("select");
selects[0].addEventListener('change', function()
{
getSelectedItem(this, row)
}, false);
};
function deleteRow(tableID)
{
for (var rowi= table.rows.length; rowi==0;) {
var row= table.rows[rowi];
var inputs= row.getElementsByTagName('chk');
for (var inputi= inputs.length; inputi0;) {
var input= inputs[inputi];
if (input.type==='checkbox' && input.checked) {
row.parentNode.remove(tableID);
break;
}
}}}
for (var keys in classes) {
category_dropdown[category_dropdown.length] = new Option(keys, keys);
}
});
</script>
</head>
<body>
<INPUT type="button" value="Add Class" id="button" />
<INPUT type="button" value="Remove Selected Classes"/>
<form id="myForm">
<TABLE id="dataTable">
<TR>
<TD>
<select id="selectCategory">
<option>Choose Class Type</option>
</select>
</TD>
<TD>
<select id="selectSubCategory">
<option>Choose Class Type First</option>
</select>
</TD>
<TD><INPUT type="checkbox" name="chk" id="input"/></TD>
</TR>
</TABLE>
</form>
<input type = "Submit" value = "Submit">
</body>
</html>
My first suggestion would be to make sure that the remove button is doing something when you click it - you've attached an event listener to the Add Class button, but the Remove Selected Classes button doesn't look like it's calling that deleteRows function.
Then, make sure that you have a reference to that table in the deleteRows function. You are passing it a table id, but the table variable reference is defined outside of the scope of that function.
Then, work on the for loop and the logic therein. It looks like you are mistaking getElementsByTagName with getElementsByName. The one you are using is concerned with the tag name (input) not the name attribute (chk).
Hope this helps a little bit!

How to get the row wise and column wise table data of a selected cell in js

[![This is a table designed using HTML][1]][1]
Hi,
In this table any cell can be selected by the user(even multiple cells).What i need is that once the submit button is pressed the corresponding row wise and column wise table data i.e B and 1pm as of this example must be stored in the database.
<script type="text/javascript">
function change()
{
var cells = document.querySelectorAll("td");
for (var i = 0; i < cells.length; i++) {
cells[i].addEventListener("click", function() {
this.className= this.className == "white" ? "green" : "white";
});
}
}
function alert()
{
var cells = document.querySelectorAll("td");
for(var i=0;i<cells.length;i++)
{
if(cells[i].className.match("green"))
{
document.getElementById('p1').innerHTML="Appointment fixed";
}
}
}
</script>
This is the js for cell selection and alert message on submit if any one of the cells is selected
I'm new to js,so someone kindly help me out with this.Thankyou.
In the HTML of each td element you can save its column name and row name like this
<td data-r="Fairlands_B" data-c="1pm" class="green"></td>
Then to get the row and column data out of the clicked td:
var place=this.dataset.r;
var time=this.dataset.c;

delete row in table with javascript

Apologies if something similar has been posted but I am trying to delete a row the button is on and not just the last row as the search results seem to give me.
I have the following code that adds to an HTML table but onclick doesn't work, the delete button doesn't work and addRow doesn't function. Why not?
java code
function addRow() {
var table = document.getElementById("createOrderTable");
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
... other cells ...
var cell4 = row.insertCell(3);
var btn = document.createElement("input");
btn.type = "button";
btn.value = "Close";
btn.onclick = deleteRow('createOrderTable', rowCount);
cell4.appendChild(btn);
}
function deleteRow(id, row) {
document.getElementById(id).deleteRow(row);
}
table code
<table id="createOrderTable" width="100%">
<tr>
<th>Count</th><th>Product</th><th>Mesh</th><th>Delete</th>
</tr>
<tr>
<td>1</td><td>OL</td><td>200</td><td><button type="button" class="close" aria-hidden="true" onclick="deleteRow('createOrderTable', 1)">×</button></td>
</tr>
</table>
if I change
btn.onclick = deleteRow('createOrderTable', rowCount );
to
btn.onclick = deleteRow('createOrderTable', rowCount + 1 );
I can get the row to show but it throws
Uncaught IndexSizeError: Failed to execute 'deleteRow' on 'HTMLTableElement': The index provided (3) is greater than the number of rows in the table (3).
and doesn't show the button. I'm confused about what I'm doing wrong here.
The row index is not static, so as you delete rows, the row index of remaining rows can change if a row with a lower index is deleted. A solution is to not use rowIndex at all, and just use DOM relationships instead.
You can get a reference to the button that was clicked by passing this to the function, then go up parent nodes until you reach a TR element and delete it, e.g.
// Helper function:
function upTo(el, tagName) {
tagName = tagName.toLowerCase();
while (el && el.parentNode) {
el = el.parentNode;
if (el.tagName && el.tagName.toLowerCase() == tagName) {
return el;
}
}
return null;
}
function deleteRow(el) {
var row = upTo(el, 'tr')
if (row) row.parentNode.removeChild(row);
}
<table>
<tr>
<td>1</td><td>OL</td><td>200</td>
<td><button type="button" onclick="deleteRow(this)">×</button></td>
</tr>
<tr>
<td>2</td><td>AB</td><td>400</td>
<td><button type="button" onclick="deleteRow(this)">×</button></td>
</tr>
</table>
You can also use event delegation and put a single listener on the table, then use the associated event object's target property to see if the event was initiated by a click on a button with class close. If so, call deleteRow and pass the element reference as a parameter as for the above.
You shoud modify your code like this:
btn.onclick = deleteRow;
And the deleteRow declaration to this:
function deleteRow() {
this.parentElement.parentElement.remove();
}
UPDATE
Check working example.
To delete the current row that the button belongs to
Change onclick of <button> to :
onclick="this.parentNode.parentNode.parentNode.deleteRow(this.parentNode.parentNode.rowIndex)"
or change button in html like:
<input type="button" onclick="deleteRow(this)">X</button>
or by JavaScript code using
btn.setAttribute('onclick','deleteRow(this)');
Delete function is like:
function deleteRow(el) {
var tbl = el.parentNode.parentNode.parentNode;
var row = el.parentNode.parentNode.rowIndex;
tbl.deleteRow(row);
}

Checking table content before adding new content

I am trying to create a table that stores users.
What I was able to build was a table where you can add and remove some users.
Now I am trying to check the content before adding a row.
If I execute the function my table will grow exponentially instead of checking the content before adding the new user.
// push on the button excecutes addRow
function addRow(){
var firstName=document.getElementById("firstName").value;
var surName=document.getElementById("surName").value;
var email=document.getElementById("email").value;
compareRows(document.getElementById('Gebruikers'));
}
//first i want to compare content of rows vs the inputfields
function compareRows(){
var table=document.getElementById("Gebruikers");
var rowCount=table.rows.length;
//check first cell of the row. when it is the same as firstName check surName
for(var i=0;i<rowCount;i++) {
var row=table.rows[i];
var vCheck=row.cells[0];
if(vCheck===firstName) {
//check second cell of the row. when it is the same as surName check email
for(var i=0;i<rowCount;i++) {
var row=table.rows[i];
var vCheck=row.cells[1];
if (aCheck===surName) {
//check third cell of the row. when it is the same as email show prompt that use allready exists.
//if email doesnt exist check next row
for(var i=0;i<rowCount;i++) {
var row=table.rows[i];
var eCheck=row.cells[2];
if (eCheck===email) {
prompt ("Deze gebruiker bestaat al!")
};
};
};
};
//when all rows have been checked for input execute insertRow function
} else {
insertRow(firstName, surName, email);
};
}
};
function insertRow(firstName, surName, email)
{
var row = document.createElement("tr");
var table = document.getElementById("Gebruikers");
table.appendChild(row);
row.appendChild(createTd(firstName));
row.appendChild(createTd(surName));
row.appendChild(createTd(email));
var cell4=row.insertCell(3);
var remove=document.createElement("input");
remove.type="checkbox";
remove.name="chkbox[]";
cell4.appendChild(remove);
}
function createTd(text) {
var td = document.createElement("td");
td.innerText = text;
return td;
}
function deleteRow(){
var table=document.getElementById("Gebruikers");
var rowCount=table.rows.length;
for(var i=0;i<rowCount;i++) {
var row=table.rows[i];
var chkbox=row.cells[3].childNodes[0];
if(null!=chkbox&&true==chkbox.checked) {
table.deleteRow(i);
rowCount--;
i--;
}
}
}
here is the HTML code:
<!DOCTYPE html>
<html>
<script src="javascript.js"></script>
<link rel="stylesheet" type="text/css" href="css.css">
<head>
<title></title>
</head>
<body>
<table class="table" id="Users">
<tr>
<td>Name</td>
<td>Surname</td>
<td>e-mail</td>
<td>remove</td>
</tr>
</table>
<br>
<form>
Name:<br>
<input type="text" id="firstName"> <br>
Surname:<br>
<input type="text" id="surName"> <br>
E-mail:<br>
<input type="text" id="email"> <br>
</form>
<br>
<button id="addButton" onclick="addRow()">add</button>
<button id="deleteButton" onclick="deleteRow()">delete</button>
</body>
</html>
from what i can see you still have call to insertRow function inside loop body, which mean that it will add as many rows as there is already in table if they don't match. What i would do is add some kind of variable which would be changed if comparing the rows will return true.
var temp = 0; if(all_rows=true){temp++;}
and after the loop i would add:
if(temp > 0) {insertRow();}
So it would be something like this:
function compareRows(){
var table=document.getElementById("Gebruikers");
var rowCount=table.rows.length;
var temp = 0;
//check first cell of the row. when it is the same as firstName check surName
for(var i=0;i<rowCount;i++) {
var row=table.rows[i];
var vCheck=row.cells[0];
if(vCheck===firstName) {
//check second cell of the row. when it is the same as surName check email
for(var i=0;i<rowCount;i++) {
var row=table.rows[i];
var vCheck=row.cells[1];
if (aCheck===surName) {
//check third cell of the row. when it is the same as email show prompt that use allready exists.
//if email doesnt exist check next row
for(var i=0;i<rowCount;i++) {
var row=table.rows[i];
var eCheck=row.cells[2];
if (eCheck===email) {
prompt ("Deze gebruiker bestaat al!")
temp++;
};
};
};
};
//when all rows have been checked for input execute insertRow function
} else {
};
}
if(temp > 0)
{
insertRow(firstName, surName, email);
}
};

jQuery find checkbox in first td

I have many tables and in that I want to do the following,
find a table which is present in class.
find first tr, first td in a table
check checkbox present first td in a table
if checkbox present in first td then add class.
Below is my code which is not working
function myFunction() {
debugger;
var FindClass = $("table.Panel");
debugger;
var FindClass = $(".Panel table.Table");
debugger;
debugger;
if (FindClass != null) {
$("#FindClass tr").find("td:first").tagname("input");
}
}
We can do this in 2 achieve this in 2 simple ways...
Find a table with the class selector. By conditional check we can add the class to the checkbox.
Implementing the complete code in a single line with out performing the conditional operations.
HTML
<table class="Panel">
<tr>
<td><input type="checkbox" /></td>
<td><p>Test</p></td>
</tr>
<tr>
<td>Second TD</td>
</tr>
</table>
jQuery (1st method)
if($('table.Panel').length > 0) {
var tblCheckbox = $('table.Panel tr:first td:first input[type=checkbox]');
if(tblCheckbox.length > 0) {
tblCheckbox.addClass('clstochkbox');
}
}
jQuery (1st method)
$('table.Panel tr:first td:first input[type=checkbox]').addClass('clstochkbox');
http://jsfiddle.net/64jv3z6d/
Check for .length property as jQuery objects are never null. And name it different.
var panelTable = $(".Panel table.Table");
if (panelTable.length) {
// panelTable has elements
}
You can do like this
var chk_box = $("table.Panel tr:first td:first")
.find('input type=["checkbox"]');
if(chk_box.length) {
$(chk_box.addClass('x')
}
We can do this in also this way.
<script type="text/javascript">
function myFunction() {
debugger;
var headerRow = $("table.Panel tr:first th:first");
debugger;
if (headerRow != null) {
var checkbox = headerRow.find("input[type=checkbox]");
if (checkbox[0].type == 'checkbox') {
headerRow.addClass('checkboxColumns');
alert('checkbox Found')
} else {
alert('not found')
}
}
}
</script>

Categories