The following code that I typed is used to add or delete rows in an html table. When I click the add button without any problem, but when I click the delete button though I want to delete a particular row I am unable to. I get an alert message stating:
"can not read property `onclick` of null "
How can I rectify this issue?
<HTML>
<HEAD>
<TITLE> Add/Remove dynamic rows in HTML table </TITLE>
<SCRIPT language="javascript">
function addRow(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;
//alert(newcell.childNodes);
switch (newcell.childNodes[0].type) {
case "text":
newcell.childNodes[0].value = "";
break;
case "checkbox":
newcell.childNodes[0].checked = false;
break;
case "select-one":
newcell.childNodes[0].selectedIndex = 0;
break;
}
}
}
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 (document.getElementById('button').onclick == true) {
if (rowCount <= 1) {
alert("Cannot delete all the rows.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
} catch (e) {
alert(e);
}
}
</SCRIPT>
</HEAD>
<BODY>
<INPUT type="button" value="Add Row" onclick="addRow('dataTable')" />
<TABLE id="dataTable" width="350px" border="1">
<TR>
<TD>
<INPUT type="button" name="button" value=delete id=delete onclick="deleteRow('dataTable')">
</TD>
</TR>
</TABLE>
</BODY>
</HTML>
The easiest way I've found to handle scenarios like these is to work with classes instead of ids, and also to use context. IDs are used as unique identifiers for items on your page. Because you will very likely have more than one 'remove button' on your page, it would be best to target them using a class name instead.
So what I would do if I were you is to include jQuery, it would make things a lot simpler for you.
Add the below line in your html document before the closing body tag.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script>
Add a 'removeRowBtn' class to your 'remove buttons'.
Then, for removing a row:
$(document).ready(function(){
$('body').on('click', '.removeRowBtn', function(){
// to make sure at least one row remains
if($('.removeRowBtn').length > 0){
$(this).parents('tr').remove();
}
});
});
And that's all you need. The above code uses context to target the parent row of the 'remove button' you are clicking on. No need to specify which table, calculate which row or how many rows are left etc.
First things first document.getElementById('button') returns undefined because you have no element in your page with id=button.
That is the error you are getting, but I think you should approach the deletion of your table rows slightly different.
The easiest way is this:
function deleteRow(elem) {
var table = elem.parentNode.parentNode.parentNode;
var rowCount = table.rows.length;
if(rowCount === 1) {
alert('Cannot delete the last row');
return;
}
// get the "<tr>" that is the parent of the clicked button
var row = elem.parentNode.parentNode;
row.parentNode.removeChild(row); // remove the row
}
and use this function as the click event handler on each button:
<table>
<tr>
<td><button onclick="deleteRow(this)">delete</button></td>
</tr>
</table>
There's no need to create deleteRow(tableID) because by doing this you are trying to override the default deleteRow function of javascript so instead of creating a deleteRow(tableID) just add 'document.getElementById('dataTable').deleteRow(this.rowIndex)' to onclick of the delete button
<input type="button" name="button" value=delete id=delete onclick="document.getElementById('dataTable').deleteRow(this.rowIndex)">
You can use below method to delete a particular row.
SCRIPT METHOD:
function deleteRow(element,tableID) {
try {
var tableElement = document.getElementById(tableID);
if(tableElement.rows.length <= 1){
alert("Cannot delete all the rows.");
return;
}
var x = element.parentElement;//td tag
x = x.parentElement;// tr tag
x.remove();
}catch(e) {
alert(e);
}
}
BUTTON ELEMENT IN TD
<TD><INPUT type="button" name="button" value=delete id=delete onclick="deleteRow(this,'dataTable')"></TD>
<div class="table-responsive">
<table class="table" id="testTable">
<thead>
<tr>
<th>Col1</th>
<th>Col2</th>
<th>Type</th>
<th>Remove</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" id="mainScript" name="mainScript"></td>
<td><input type="text" id="rollBackScript" name="rollBackScript"></td>
<td><select name="type" id ="type" >
<option value="Automated" selected >Automated</option>
<option value="Manual" >Manual</option>
</select>
</td>
<td><input type="button" class="btn btn-danger" value="Delete" onclick="deleteRow(this);"></td>
</tr>
</tbody>
</table>
</div>
</div>
<div class="row" align="left">
<input type="button" class="btn btn-success" value="Add Row" onclick="addRow('scriptsTable')" />
</div>
JavaScript functions
<script>
function addRow(tableId) {
var table = document.getElementById(tableId);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[1].cells.length;
for(var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[1].cells[i].innerHTML;
//alert(newcell.childNodes);
switch(newcell.childNodes[0].type) {
case "text":
newcell.childNodes[0].value = "";
break;
case "checkbox":
newcell.childNodes[0].checked = false;
break;
case "select-one":
newcell.childNodes[0].selectedIndex = 0;
break;
case "button":
newcell.childNodes[0].value = "Delete";
break;
}
}
}
function deleteRow(deleteBtn) {
var table = document.getElementById('scriptsTable');
if(table.rows.length <= 2){
alert("Cannot delete all the rows.");
return;
}
if (typeof(deleteBtn) == "object") {
$(deleteBtn).closest("tr").remove();
} else {
return false;
}
}
</script>
Try this one. this is working example
<table id="example" class="table table-striped table-bordered" cellspacing="0" width="100%">
<thead>
<tr>
<th>ID</th>
<th>Name</th>
<th>Position</th>
<th>Action</th>
</tr>
</thead>
<tbody>
<tr>
<td>1</td>
<td>Tiger Nixon</td>
<td>System Architect</td>
<td><button>Delete</button></td>
</tr>
</tbody>
</table>
<script>
$(document).ready(function () {
var table = $('#example').DataTable({
"columns": [
null,
null,
null,
{
"sortable": false
}
]
});
});
$('#example').on("click", "button", function(){
console.log($(this).parent());
table.row($(this).parents('tr')).remove().draw(false);
});
</script>
Related
I have nested tables parent and child table. Both tables can add rows on button click if needed. Problem i am facing is this when a row is added in parent table then in that row child table button not works. they work fine for child table of first row in parent table and not works for the second row. please see snippet for demonstration.
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[1].cells.length;
for(var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[1].cells[i].innerHTML;
//alert(newcell.childNodes);
switch(newcell.childNodes[0].type) {
case "text":
newcell.childNodes[0].value = "";
break;
case "checkbox":
newcell.childNodes[0].checked = false;
break;
case "select-one":
newcell.childNodes[0].selectedIndex = 0;
break;
}
}
}
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("Cannot delete all the rows.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}catch(e) {
alert(e);
}
}
function addRow1(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[1].cells.length;
for(var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[1].cells[i].innerHTML;
//alert(newcell.childNodes);
switch(newcell.childNodes[0].type) {
case "text":
newcell.childNodes[0].value = "";
break;
case "checkbox":
newcell.childNodes[0].checked = false;
break;
case "select-one":
newcell.childNodes[0].selectedIndex = 0;
break;
}
}
}
function deleteRow1(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("Cannot delete all the rows.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}catch(e) {
alert(e);
}
}
table {
border-collapse: collapse;
width: 100%;
border:1px solid #1E90FF;
}
th, td {
text-align: left;
padding: 8px;
border:1px solid #1E90FF;
}
th {
background-color: #1E90FF;
color: white;
}
<TABLE id="dataTable">
<thead>
<tr>
<th style="text-align: center;"> Select </th>
<th style="text-align: center;"> <b>Size</b> </th>
<th style="text-align: center;"> <b>Color & Quantity</b> </th>
</tr>
</thead>
<tbody>
<tr id='C1' class='customer'>
<td><input type="checkbox" name="chk"/></td>
<td><select name="size[]" id="size" required="" >
<option value="">Select Size</option></select></td>
<td>
<TABLE style="margin-top: 20px;" id="dataTable1" width="400px" border="1">
<thead>
<th> Select </th>
<th> <b>Color Quantity</b> </th>
</thead>
<TR>
<TD><INPUT type="checkbox" name="chk"/></TD>
<TD>
<select name="color[]" required="" >
<option value="">Select Color</option>
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
<option value="Black">Black</option>
</select>
<input type="number" name="dress_quantity[]" class="qty1" placeholder="Size Quantity" value="" required="">
</TD>
</TR>
</TABLE>
<INPUT type="button" value="Add Row" onclick="addRow1('dataTable1')" />
<INPUT type="button" value="Delete Row" onclick="deleteRow1('dataTable1')" />
</td>
</tr>
</tbody>
</TABLE>
<INPUT type="button" value="Add Row" onclick="addRow('dataTable')" />
<INPUT type="button" value="Delete Row" onclick="deleteRow('dataTable')" />
Problem:
You are copying/cloning the HTML of parent to child rows and this in-turns assigns parent id (of first row based on your code) to child rows.
Code causing issue in addRow method:
newcell.innerHTML = table.rows[1].cells[i].innerHTML;
Solution:
Assign different id's to the new child table and buttons when you click on parent's Add Row button.
Replace the below line in addRow method from:
newcell.innerHTML = table.rows[1].cells[i].innerHTML;
to
if (i == colCount - 1) //last column which adds child table
{
//Get child table id of first row
var tableID = table.rows[1].cells[i].childNodes[1].getAttribute("id");
//Replace all occurances of parent table id's with new unique table id for child table before writing the information to DOM
newcell.innerHTML = table.rows[1].cells[i].innerHTML.replace(new RegExp(tableID,"g"), "dataTable" + Math.floor((Math.random() * 1000) + 1));
}
else //For other columns there is no need to assign unique id for controls
newcell.innerHTML = table.rows[1].cells[i].innerHTML;
Note: I am generating random number using Math.floor((Math.random() * 1000) + 1)). You may want to change to logic of your own.
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[1].cells.length;
for (var i = 0; i < colCount; i++) {
var newcell = row.insertCell(i);
if (i == colCount - 1) //last column
{
//Get child table id of first row
var tableID = table.rows[1].cells[i].childNodes[1].getAttribute("id");
newcell.innerHTML = table.rows[1].cells[i].innerHTML.replace(new RegExp(tableID,"g"), "dataTable" + Math.floor((Math.random() * 1000) + 1));
}
else
newcell.innerHTML = table.rows[1].cells[i].innerHTML;
//alert(newcell.childNodes);
switch (newcell.childNodes[0].type) {
case "text":
newcell.childNodes[0].value = "";
break;
case "checkbox":
newcell.childNodes[0].checked = false;
break;
case "select-one":
newcell.childNodes[0].selectedIndex = 0;
break;
}
}
}
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("Cannot delete all the rows.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
} catch (e) {
alert(e);
}
}
function addRow1(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[1].cells.length;
for (var i = 0; i < colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[1].cells[i].innerHTML;
//alert(newcell.childNodes);
switch (newcell.childNodes[0].type) {
case "text":
newcell.childNodes[0].value = "";
break;
case "checkbox":
newcell.childNodes[0].checked = false;
break;
case "select-one":
newcell.childNodes[0].selectedIndex = 0;
break;
}
}
}
function deleteRow1(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("Cannot delete all the rows.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
} catch (e) {
alert(e);
}
}
<style type="text/css">
table {
border-collapse: collapse;
width: 100%;
border: 1px solid #1E90FF;
}
th,
td {
text-align: left;
padding: 8px;
border: 1px solid #1E90FF;
}
th {
background-color: #1E90FF;
color: white;
}
</style>
<TABLE id="dataTable">
<thead>
<tr>
<th style="text-align: center;"> Select </th>
<th style="text-align: center;"> <b>Size</b> </th>
<th style="text-align: center;"> <b>Color & Quantity</b> </th>
</tr>
</thead>
<tbody>
<tr id='C1' class='customer'>
<td><input type="checkbox" name="chk" /></td>
<td><select name="size[]" id="size" required="">
<option value="">Select Size</option></select></td>
<td>
<TABLE style="margin-top: 20px;" id="dataTable1" width="400px" border="1">
<thead>
<th> Select </th>
<th> <b>Color Quantity</b> </th>
</thead>
<TR>
<TD>
<INPUT type="checkbox" name="chk" />
</TD>
<TD>
<select name="color[]" required="">
<option value="">Select Color</option>
<option value="Red">Red</option>
<option value="Green">Green</option>
<option value="Blue">Blue</option>
<option value="Black">Black</option>
</select>
<input type="number" name="dress_quantity[]" class="qty1" placeholder="Size Quantity" value="" required="">
</TD>
</TR>
</TABLE>
<INPUT type="button" value="Add Row" onclick="addRow1('dataTable1')" />
<INPUT type="button" value="Delete Row" onclick="deleteRow1('dataTable1')" />
</td>
</tr>
</tbody>
</TABLE>
<INPUT type="button" value="Add Row" onclick="addRow('dataTable')" />
<INPUT type="button" value="Delete Row" onclick="deleteRow('dataTable')" />
I need help in filling the dynamically generated text boxes using jquery autocomplete.
Workflow:
1.On clicking add row button a row will be inserted.
2.On the inserted row,the product text box should be filled through auto complete.The same way all the dynamically generated text boxes should be filled by auto complete
Issue:
I have used the jquery auto complete function to fill the text boxes,but the auto complete function is working only for the text box in the first row.I need to fill all the dynamically created text boxes through auto complete function.
This is my code.
<html>
<head>
<script type="text/javascript" src="JS/jquery-1.4.2.min.js"></script>
<script src="JS/jquery.autocomplete.js"></script>
<script>
jQuery(function(){
$("#product").autocomplete("Productset.jsp");
});
</script>
<script type="text/javascript">
function addRow(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[1].cells[i].innerHTML;
//alert(newcell.childNodes);
switch(newcell.childNodes[0].type) {
case "text":
newcell.childNodes[0].value = "";
break;
case "select-one":
newcell.childNodes[0].selectedIndex = 0;
break;
}
}
}
function deleteRow(tableID) {
try {
var table = document.getElementById(tableID);
var rowDelete = table.rows.length - 1;
if (rowDelete > 1)
table.deleteRow(rowDelete);
else
alert("Cannot delete all the rows.")
}
catch(e) {
alert(e);
}
}
</script>
</head>
<body>
<form>
<input type="button" value="Add Row" onclick="addRow('dataTable')" />
<input type="button" value="Delete Row" onclick="deleteRow('dataTable')" />
<br/>
<br/>
<table id="dataTable" align="center" width="350px" border="1">
<tr>
<th> Product Name</th>
<th>Quantity</th>
<th> Brand</th>
</tr>
<tr>
<td> <input type="text" name="pname" id="product" value="" /></td>
<td><input type="text" name="qty" value=""/></td>
<td><select name="brand"/>
<select>
<option value="select">SELECT</option>
</select>
</td>
</table>
</form>
</body>
</html>
Productset.jsp
<%#page contentType="text/html" pageEncoding="UTF-8"%>
<%#page import="java.sql.*"%>
<%#page import="java.util.*"%>
<%
try{
String s[]=null;
Class.forName("com.mysql.jdbc.Driver");
Connection con =DriverManager.getConnection("jdbc:mysql://localhost:3306/pdt","root","root");
Statement st=con.createStatement();
ResultSet rs = st.executeQuery("select distinct product from productlist");
List li = new ArrayList();
while(rs.next())
{
li.add(rs.getString(1));
}
String[] str = new String[li.size()];
Iterator it = li.iterator();
int i = 0;
while(it.hasNext())
{
String p = (String)it.next();
str[i] = p;
i++;
}
//jQuery related start
String query = (String)request.getParameter("q");
int cnt=1;
for(int j=0;j<str.length;j++)
{
if(str[j].toUpperCase().startsWith(query.toUpperCase()))
{
out.print(str[j]+"\n");
if(cnt>=5)// 5=How many results have to show while we are typing(auto suggestions)
break;
cnt++;
}
}
//jQuery related end
rs.close();
st.close();
con.close();
}
catch(Exception e){
e.printStackTrace();
}
%>
You need to call autocomplete in jquery 'on' function
$(document).on("focus","#product",function(e){
$(this).autocomplete("Productset.jsp");
});
When you add a new row you should call again the autocomplete function
$("#button").click(function(e) {
addRow();
$(".auto").autocomplete({
source: datas
});
});
https://jsfiddle.net/w78L1ho2/
if your Productset.jsp is not moving I recommand to call it only once.
To fill your datas with your text file you can do something like this
(convert text file to array comes from https://stackoverflow.com/a/6833016/5703316):
var datas = [];
function func(data) {
datas.push(data);
}
function readLines(input, func) {
var remaining = '';
input.on('data', function(data) {
remaining += data;
var index = remaining.indexOf('\n');
var last = 0;
while (index > -1) {
var line = remaining.substring(last, index);
last = index + 1;
func(line);
index = remaining.indexOf('\n', last);
}
remaining = remaining.substring(last);
});
input.on('end', function() {
if (remaining.length > 0) {
func(remaining);
}
});
}
$.get("Productset.jsp").done(function(result) {
readLines(result, func);
});
In my code the dynamically created text box doesn't take the jquery auto complete function.So including the auto complete function inside the addrow() method will fill the dynamically created text boxes with the auto complete data.
The id selector will only fill the first text box with the auto complete data.So use this $('input[name="product"]').auto complete("Productset.jsp"); in the jquery function to fill all the text boxes.
This is the complete code.
<html>
<head>
<script type="text/javascript" src="JS/jquery-1.4.2.min.js"></script>
<script src="JS/jquery.autocomplete.js"></script>
<script>
jQuery(function(){
$("#product").autocomplete("Productset.jsp");
});
</script>
<script type="text/javascript">
function addRow(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[1].cells[i].innerHTML;
//alert(newcell.childNodes);
switch(newcell.childNodes[0].type) {
case "text":
newcell.childNodes[0].value = "";
jQuery(function(){
$('input[name="product"]').autocomplete("Productset.jsp");
});
break;
case "select-one":
newcell.childNodes[0].selectedIndex = 0;
break;
}
}
}
</script>
</head>
<body>
<form>
<input type="button" value="Add Row" onclick="addRow('dataTable')" />
<input type="button" value="Delete Row" onclick="deleteRow('dataTable')" />
<br/>
<br/>
<table id="dataTable" align="center" width="350px" border="1">
<tr>
<th> Product Name</th>
<th>Quantity</th>
<th> Brand</th>
</tr>
<tr>
<td> <input type="text" name="product" id="product" value="" /></td>
<td><input type="text" name="qty" value=""/></td>
<td><select name="brand"/>
<select>
<option value="select">SELECT</option>
</select>
</td>
</table>
</form>
</body>
</html>
I am creating a form where the user can dynamically add rows. Everything works fine except one thing: I cannot add class to certain input element created by the user:
This is how I add rows:
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
var row = table.insertRow(rowCount);
var colCount = table.rows[1].cells.length;
for(var i=0; i<colCount; i++) {
var newcell = row.insertCell(i);
newcell.innerHTML = table.rows[1].cells[i].innerHTML;
//alert(newcell.childNodes);
switch(newcell.childNodes[0].type) {
case "text":
newcell.childNodes[0].value = "";
break;
case "checkbox":
newcell.childNodes[0].checked = false;
break;
case "select-one":
newcell.childNodes[0].selectedIndex = 0;
break;
}
}
}
(Courtesy of this site)
Form:
<TABLE id="dataTable" width="350px" border="1" class="plantable">
<TR>
<TH></TH>
<TH>From</TH>
<TH>To</TH>
<TH>When</TH>
</TR>
<TR>
<TD><INPUT type="checkbox" name="chk[]"/></TD>
<TD><INPUT type="text" name="from[]"/></TD>
<TD><INPUT type="text" name="to[]"/></TD>
<TD><INPUT type="text" name="when[]" class="datepicker"/></TD>
</TR>
</TABLE>
<br/>
<INPUT type="button" value="Add Row" onclick="addRow('dataTable')" class="add_remove_row" />
Here I gave an class="datepicker" to the when named input box. But the next rows do not have this property.
If that matters, by click on that input object, I open a datepicker with the help of this site. When I click the when named input box in the rows I dynamically create, the datepicker does not show hence it does not inherit the class property. It works fine for the first row which is not dynamically created.
How do I add the class to the element?
I have an HTML table with insert and delete row functionality and its working perfectly. But delete functionality works with checkbox + delete button.
When i want to delete a row, first i checked the checkbox and then press delete button. I want to make it directly with delete button. Below is my 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("Cannot delete all the rows.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
} catch(e)
{
alert(e);
}
getValues();
}
<a onclick="deleteRow('dataTable')">Delete Row</a>
<table id="dataTable">
<tr>
<td><input type="checkbox" name="chk"/></td>
<td><input type="text" name="Name"></td>
</tr>
</table>
Note : Atleast 1 row should be there (Cannot delete all the rows)
If you want to use one button, a usable solution is to select/unselect the rows to be deleted onclick. This way multi select and delete is also supported. For example,
http://jsfiddle.net/Nt4wZ/
js
function selectRow(row) {
if (row.className.indexOf("selected") != -1) {
row.className = row.className.replace("selected", "");
} else {
row.className += " selected";
}
}
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 (row.getElementsByTagName("input")[0].className.indexOf("selected")!=-1) {
if (rowCount <= 1) {
alert("Cannot delete all the rows.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
} catch (e) {
alert(e);
}
//getValues();
}
html
<a onclick="deleteRow('dataTable')">Delete Row</a>
<table id="dataTable">
<tr>
<!-- <td><input type="checkbox" name="chk"/></td> -->
<td>
<input type="text" name="Name" onclick="selectRow(this)" />
</td>
</tr>
<tr>
<!-- <td><input type="checkbox" name="chk"/></td> -->
<td>
<input type="text" name="Name" onclick="selectRow(this)" />
</td>
</tr>
</table>
css
input.selected {
border-color:lightgreen;
}
EDIT - response to comments
If you want to have a delete button for each row and use that instead, you can do something like the following,
http://jsfiddle.net/GRgMb/
html
<table id="dataTable">
<tr>
<!-- <td><input type="checkbox" name="chk"/></td> -->
<td>
<input type="text" name="Name" /><input type="button" value="delete" onclick="deleteRow('dataTable',this)" />
</td>
</tr>
<tr>
<!-- <td><input type="checkbox" name="chk"/></td> -->
<td>
<input type="text" name="Name" /><input type="button" value="delete" onclick="deleteRow('dataTable',this)" />
</td>
</tr>
</table>
js
function deleteRow(tableID,currentRow) {
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 (row==currentRow.parentNode.parentNode) {
if (rowCount <= 1) {
alert("Cannot delete all the rows.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
} catch (e) {
alert(e);
}
//getValues();
}
This code is an example:
$(document).on('click', 'img.imgdel', function deleteRow() {
$(this).closest('tr').remove();
return false;
});
https://codepen.io/dionejpmc/pen/vYxLdyX
I've run into a problem with adding and deleting blank rows in javascript... it's a nesting issue and unique id issue.
To summarize, I have three form fields. Field1, Amount1, Amount2. Field1 can have multiple Amount1 & Amount2. There can be multiple Field1 as well, which also can have mutiple Amount1, Amount2. The problem is that my "Add" buttons copies the extra Amount1, Amount2 (when exists). Just to explain, the "Add row" adds Amount1,Amount2. The "Delete Row" deletes Amount1,Amount2 when the checkbox is checked.
When I click the "Add" button, I want a new Field1, Amount1, Amount2 but no additional Amount1,Amount2. And when I click "Add Row" or "Delete Row" in the additional sets of form fields, I want it to add or delete the Amount1,Amount2 in that particular set.
I need to assign a unique identifier to each entire row to get this to work but cannot figure it out.
Here is my code, which will probably make more sense if it's executed.
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN"
"http://www.w3.org/TR/html4/loose.dtd"><head>
<script type="text/javascript">
function addRow(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.row[0].cells [i].innerHTML; //alert (newcell.childNodes);
switch(newcell.childNodes[0].type) {
case "text":
newcell.childNodes[0].value = "";
break;
case "checkbox":
newcell.childNodes[0].checked = false;
break;
case "select-one":
newcell.childNodes[0].selectedIndex = 0;
break;
}
}
}
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("Cannot delete all the rows.");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}catch(e)
{
alert(e);
}
}
var _counter = 0;
function Add() {
_counter++;
var oClone = document.getElementById("template").cloneNode(true);
oClone.id += (_counter + "");
document.getElementById("placeholder").appendChild(oClone);
}
</script>
</head>
<body>
<fieldset id="fieldset">
<div id="placeholder">
<div id="template">
<br>
<table id= "act_legis">
<tr>
<td>Field1:</td>
<td>Amount1:</td>
<td>Amount2:</td>
<td> </td>
</tr>
</table>
<table id= "act">
<tr>
<td>
<button type="button" name="Submit"
align = "left" onclick="Add();">Add</button>
<input name="Field1" type="text" size="4" maxlength="4"/></td>
</tr>
</table>
<table id= "legis_amounts">
<tr>
<td>
<input type="checkbox" name="chk"/>
<input name="Amount1" type="text" size="10"maxlength="18"/>
</td>
<td>
<input name="Amount2" type="text" size="10" maxlength="18"/>
</td>
</tr>
</table>
<table>
<tr>
<td>
<input type="button" onclick="addRow('legis_amounts');
return false;" value = "add row"/>
<input type="button" value = "delete row" onclick="deleteRow
('legis_amounts');return false;" />
</td>
</tr>
</table>
</div> <!-- template -->
</div> <!-- placeholder -->
</fieldset>
<table>
<tr>
<td><p> </p>
</td>
</tr>
</table>
</body>
</html>