Deleting HTML tables rows - javascript

I know there are like thousands of answers on Stack Overflow about this specific topic, but I have been reading them for 3 days and nights already trying to apply solutions to my code with no success.
The problem is that addRow works fine, but DeleteRow doesn't work at all.
Here is my HTML:
<input type="button" value="add" onClick="addRow('dataTable')" />
<input type="button" value="delete" onclick="deleteRow(this)"/>
<p></p>
</p>
</table>
<table id="dataTable" class="cv" border="1">
<tr>
<td>
<input type="text" style="width:100%" placeholder="ievadiet valodu">
</td>
<td>
<select id="BX_gender" name="BX_gender" required="required">
<option>dzimtā valoda</option>
<option>teicami</option>
<option>labi</option>
<option>viduvēji</option>
<option>pamatzināšanas</option>
</select>
</td>
<td>
<select id="BX_gender" name="BX_gender" required="required">
<option>teicami</option>
<option>labi</option>
<option>viduvēji</option>
<option>pamatzināšanas</option>
</select>
</td>
<td>
<select id="BX_gender" name="BX_gender" required="required">
<option>teicami</option>
<option>labi</option>
<option>viduvēji</option>
<option>pamatzināšanas</option>
</select>
</td>
</tr>
</table>
<div class="clear"></div>
</fieldset>
javascript:
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
if (rowCount < 5) {
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("Maksimālais ierakstu skaits ir 7.");
}
}
function DeleteRow(o) {
//no clue what to put here?
var p = o.parentNode.parentNode;
p.parentNode.removeChild(p);
}
Here is a fiddle with code working (only the addRow function): http://jsfiddle.net/7AeDQ/690/

Assuming you want to delete the last row, you can use something like this
function deleteRow() {
var table = document.getElementById("dataTable");
var tbody = table.tBodies[0];
tbody.removeChild(tbody.lastChild);
}
Updated fiddle here
Using something like this, you don't need to traverse the DOM using parentNode.parentNode...

Related

How to count 1 option selected in dropdown from different rows added and display in textbox?

How to count 1 option selected in dropdown from different rows and display count in textbox?
I would like to count total value casualties of different rows and display count of total value casualties in textbox id injury.
Codes for dropdownlist && textbox && add row:
<select name="type" id="dd">
<option>Select a Type</option>
<option value="casualties">Casualties</option>
<option value="notcasualties">Not Casualties</option>
</select>
</select>
<label>Casualties:</label><input type="text" id="injury">
<btn><input type="button" value="addrow" onclick="addrow('dataTable2')" /></btn>
This codes are only able to display count = 1 in textbox id injury for the first row but not the added rows. I would like to total up count of value casualties after different rows are added. Could anyone help me.
$('#dd').change(function(){
var count = $('#dd option:selected').length;
$('.injury').val(count);
});
Thanks in advance!
Add onchange="select($(this).val())" in select tag and following function in script
function select(value){
if(value==="casualties"){
$("#injury").val(parseInt($("#injury").val())+1);
}
else{
$("#injury").val(parseInt($("#injury").val())-1);
if($("#injury").val()<0)
$("#injury").val("0");
}
}
and remove
$('#dd').change(function(){
var count = $('#dd option:selected').length;
$('.injury').val(count);
});
I made some changes that full fill your purpose
<html>
<head><title>table example</title></head>
<body>
<table id="dataTable2">
<tr>
<th></th>
<TH>Admin No/Staff ID:</TH>
<TH>Name:</TH>
<TH>Contact No:</TH>
<TH>Types of People Involved:</TH>
</TR>
<tr>
<td><input type="checkbox" name="checkbox[]"></td>
<TD><input type="text" name="id[]" id="id" /></TD>
<TD><input type="text" name="names[]" id="names"></TD>
<TD><input type="text" name="contacts[]" id="contacts" /> </TD>
<TD>
<select name="type" id="dd" class="selectpicker" data-style="select-with-transition" title="News Type" data-size="7" onchange="show()">
<option value="">Select a Type</option>
<option value="casualties" class="casualties-element">Casualties</option>
<option value="ncasualties">Non-Casualties</option>
<option value="witness">Witness</option>
</select>
</TD>
</tr>
</table>
<p>
<INPUT type="button" value="Add Row" onclick="addRow()" />
</p>
<table id="dataTable1" style="cellpadding:20px;">
<tr>
<th></th>
<TH>Admin No/Staff ID:</TH>
<TH>Name:</TH>
<TH>Contact No:</TH>
<TH>Types of People Involved:</TH>
</tr>
</table>
<p>
<label>No. of Casualties:</label>
<input type="text" name="injury" id="injury" class="injury span2" onClick="show();">
</p>
<script>
var count = 0;
function addRow() {
alert("test");
var table1 = document.getElementById('dataTable1');
var table = document.getElementById('dataTable2');
var did = document.getElementById('id').value;
var dname = document.getElementById('names').value;
var dcontact = document.getElementById('contacts').value;
var dddl = document.getElementById('dd');
var ddlvalue = dddl.options[dddl.selectedIndex].value;
if (ddlvalue == 'casualties') { count++; }
document.getElementById('injury').value = count;
var rowCount = table.rows.length;
//var row = table.insertRow(rowCount);
var row = table1.insertRow(1);
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 (i) {
case 0:
newcell.innerHTML = did;
break;
case 1:
newcell.innerHTML = dname;
break;
case 2:
newcell.innerHTML = dcontact;
break;
case 3:
newcell.innerHTML = ddlvalue;
break;
}
}
}
</script>
</body>
</html>

Function in JavaScript doesn't work while the other function works

I have a form written in HTML. In this form there are 2 buttons, and a table. Each row in the table contains a checkbox, and 2 text fields.
The buttons are to add and remove rows from the table. The remove button apply only to rows where their checkbox is checked. They have an onClick method that refers to 2 methods written in JavaScript on a <script> tag below, addRow(tableID) and deleteRow(tableID).
The addRow(tableID) works when I click its buttons, but nothing happens when I click the remove button, which refers to deleteRow(tableID) method.
This is the code of the form:
<form action="Page2.php" method="post" enctype="multipart/form-data">
<!-- Contacts Details -->
<p>
<input type="button" value="Add Contact" onClick="addRow('contacts')" />
<input type="button" value="Remove Contact" onClick="deleteRow('contacts')" />
<p>(All actions apply only to entries with check marked check boxes only.)</p>
</p>
<table id="contacts" class="form" border="1">
<tbody>
<tr>
<p>
<td>
<input type="checkbox" name="chk[]" checked="checked" />
</td>
<td>
<label>Address</label>
<input type="text" name="ADDRESS[]" />
</td>
<td>
<label for="PHONE_NUMBER">Phone Number</label>
<input type="text" class="small" name="PHONE_NUMBER[]" />
</td>
</p>
</tr>
</tbody>
</table>
<script>
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
if (rowCount < 10) {
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 Contacts Number is 10");
}
}
function deleteRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for (var i = 0; i < rowCount; i++) {
debugger;
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
if (null != chkbox && true == chkbox.checked) {
if (rowCount <= 1) {
alert("Cannot Remove all Contacts");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}
</script>
<!-- Form Sending -->
<input type="submit" value="Proceed">
</form>
EDIT #!:
I have just debugged the above code, and I found out that the variables chkbox and row from the deleteRow(tableID) method are shown in the debugger as undefined.
What can I do to fix this?
The problem is that using row.cells[0].childNodes[0] is an extremely brittle way to find nodes. You are retrieving a text node instead of the checkbox. Using
childNodes will break with even minimal changes to the HTML.
A more reliable way is to query for the element you are looking for
var chkbox = row.cells[0].querySelector('[type=checkbox]')
<form action="Page2.php" method="post" enctype="multipart/form-data">
<!-- Contacts Details -->
<p>
<input type="button" value="Add Contact" onClick="addRow('contacts')" />
<input type="button" value="Remove Contact" onClick="deleteRow('contacts')" />
<p>(All actions apply only to entries with check marked check boxes only.)</p>
</p>
<table id="contacts" class="form" border="1">
<tbody>
<tr>
<p>
<td>
<input type="checkbox" name="chk[]" checked="checked" />
</td>
<td>
<label>Address</label>
<input type="text" name="ADDRESS[]" />
</td>
<td>
<label for="PHONE_NUMBER">Phone Number</label>
<input type="text" class="small" name="PHONE_NUMBER[]" />
</td>
</p>
</tr>
</tbody>
</table>
<script>
function addRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
if (rowCount < 10) {
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 Contacts Number is 10");
}
}
function deleteRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
for (var i = 0; i < rowCount; i++) {
debugger;
var row = table.rows[i];
var chkbox = row.cells[0].querySelector('[type=checkbox]');
if (null != chkbox && true == chkbox.checked) {
if (rowCount <= 1) {
alert("Cannot Remove all Contacts");
break;
}
table.deleteRow(i);
rowCount--;
i--;
}
}
}
</script>
<!-- Form Sending -->
<input type="submit" value="Proceed">
</form>

Jquery - add new rows table into wrong div

I am pretty new to jquery. I have the following code. Here I wants to get new rows in the table on clicking add button in Fill 3. I succeend to add that row, but when I get new divs then I wants to get new rows in the table on clicking add button in Fill 3. It added into wrong div.
can someone tell me what mistake I've done here?
var id = 0; //global id to create unique id
$(document).ready(function() {
//attach click event to element/button with id add and remove
$("#add,#remove").on('click', function() {
var currentElemID = $(this).attr('id'); //get the element clicked
if (currentElemID == "add") { //if it is add elem
var cloneParent = $("#dataTes").clone(); //clone the dataTes element
id=$("div[id^=dataTes]").length + 1;//get the count of dataTes element
//it will be always more than last count each time
cloneParent.find('[id]').each(function() {
//loop through each element which has id attribute in cloned set and replace them
//with incremented value
var $el = $(this); //get the element
$el.attr('id', $el.attr('id') + id);
//ids would now be add1,add2 etc.,
});
cloneParent.attr('id', cloneParent.attr('id') + id);//replace cloneParent id
cloneParent.appendTo('#result');//append the element to fieldset
$("#remove").show();//show remove button only if there is more than one dataTes element
} else {
$("div[id^=dataTes]:last").remove();
//just remove the last dataTes
//[id^=dataTes]:last annotates remove last div whose id begins with dataTes
//remember we have id like dataTes1,dataTes2 etc
if($("div[id^=dataTes]").length==1){
//check if only one element is present
$("#remove").hide();//if yes hide the remove button
}
}
});
});
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;
}
}
function deleteRow(tableID) {
var table = document.getElementById(tableID);
var rowCount = table.rows.length;
if (rowCount > 1) {
table.deleteRow(rowCount - 1);
}
else {
alert("Tidak dapat menghapus semua baris!");
}
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<fieldset id="result">
<legend>Test</legend>
<input type="submit" class="button" id="add" value="+" title="#">
<input type="submit" class="button" id="remove" value="-" style="display:none;" title="#">
<!--hide the remove button with display:none initially-->
<div id="dataTes">
<table align="center" cellpadding="3" cellspacing="0" style="border-collapse:collapse;margin-top:10px;" width="97%">
<tr>
<td width="100px">Test</td>
<td width="2px">:</td>
<td>
<input type="text" name="usrname">
</td>
</tr>
<table align="center" cellpadding="3" cellspacing="0" style="border-collapse:collapse;margin-top:5px;margin-left:40px;" width="97%">
<tr>
<td width="2px"></td>
<td width="100px">Fill 1</td>
<td width="2px">:</td>
<td>
<input type="text" name="usrname">
</td>
</tr>
<tr>
<td width="2px"></td>
<td width="100px">Fill 2</td>
<td width="2px">:</td>
<td>
<input type="text" name="usrname">
</td>
</tr>
<table id="dataIP" align="center" cellpadding="3" cellspacing="0" style="border-collapse:collapse;margin-left:40px;" width="97%">
<tr>
<td width="2px"></td>
<td width="100px">Fill 3</td>
<td width="2px">:</td>
<td width="2px">
<input type="text" name="usrname">
</td>
<td>
<input type="submit" class="button" value="+" onClick="addRow('dataIP')" title = "#">
<input type="submit" class="button" value="-" onClick="deleteRow('dataIP')" title = "#">
</td>
</tr>
</table>
</table>
</table>
</div>
</fieldset>
Thanks in advance!
<table id="dataIP" align="center" cellpadding="3" cellspacing="0" style="border-collapse:collapse;margin-left:40px;" width="97%">
<tr>
<td width="2px"></td>
<td width="100px">Fill 3</td>
<td width="2px">:</td>
<td width="2px">
<input type="text" name="usrname">
</td>
<td>
<input type="submit" class="button" value="+" onClick="addRow('dataIP')" title = "#">
<input type="submit" class="button" value="-" onClick="deleteRow('dataIP')" title = "#">
</td>
</tr>
</table>`
so what will we do here is that we will change addRow(this) instead of addRow('dataIp') because we know that "this" keyword has a high priority in terms of passing the ID of the element .. the "this" keyword has a general purpose vs passing of id into a function .. just try changing all parameter to the "this".
function addRow(tableID) {
var par = tableID.parentNode.parentNode.parentNode.id;
var table = document.getElementById(par);
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;
}
this is what ive done when I change the parameter of the add and delete function in your input i get the param parent node the element for the purpose of specific element inside the parent element...
}
by the way.. you must change your third index table to tbody. the result of getting the parentnode will be a tbody. because putting table inside a table is redundant window read it as tbody
we must follow the rule
<table>
<tbody>
</tbody>
<tfoot>
</tfoot>
</table>

Struggling with DOM elements

I have an html table in my .aspx page which looks as follows:
<table id="quotationsListTable" class="quoteTbl" width="100%" border="1">
<tr>
<th></th>
<th>REF</th>
<th>Name</th>
<th>Arrival</th>
<th>Time</th>
<th>Departure</th>
<th>Time</th>
<th>Curr</th>
<th>Sale</th>
<th>Cost</th>
</tr>
<tr>
<td><input type="checkbox" name="chk"/></td>
<td> 1 </td>
<td><input type="text" style="width: 50px" /> </td>
<td><input type="text" style="width: 150px"/> </td>
<td> <input type="text" style="width: 50px"/> </td>
<td> <input type="text" style="width: 50px"/> </td>
<td> <input type="text" style="width: 50px"/> </td>
<td> <input type="text" style="width: 50px"/> </td>
<td> <input type="text" style="width: 50px"/> </td>
<td> <input type="text" style="width: 50px"/> </td>
</tr>
</table>
I also have a javascript function for deleting all the rows in my table, calling my by element ID "quotationsListTable".
The javascript function which stays in a separate .js file is a follows:
deleteAllrows('quotationsListTable');
function deleteAllrows(tableID) {
try {
var table = document.getElementByID(tableID);
var rowCount = table.rows.length;
for (var i = 1; i < rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
table.deleteRow(i);
rowCount--;
i--;
}
} catch (e) {
alert(e);
}
}
The problem at hand is that my js function cannot retrieve the table by id, the error message that is thrown is 'undefined'.
It's document.getElementById note the small d
var table = document.getElementById(tableID);
https://developer.mozilla.org/en-US/docs/DOM/document.getElementById
I suggest that you include the jquery library and remove the rows with single line .. check this fiddle http://jsfiddle.net/SamirAdel/DyXHt/
deleteAllrows('quotationsListTable');
function deleteAllrows(tableID) {
$("#"+tableID+"tr:gt(0)").remove()
}
You should set your function after the page content is ready.
And please, change your "getElementByID" to "getElementById", D um lowercase.
Try to use jQuery, is an easy way.
See:
<script src="http://code.jquery.com/jquery-1.9.1.min.js"></script>
<script>
$().ready(function(){
deleteAllrows();
function deleteAllrows() {
try {
var table = document.getElementById('quotationsListTable');
alert(table);
var rowCount = table.rows.length;
for (var i = 1; i < rowCount; i++) {
var row = table.rows[i];
var chkbox = row.cells[0].childNodes[0];
table.deleteRow(i);
rowCount--;
i--;
}
} catch (e) {
alert(e);
}
}
});
</script>

javascript dynamically add delete row nested

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>

Categories