Select box not changing while dynamically adding rows in a table - javascript

Hi iam able to add rows dynamically from the table below using javascript but the onchange function fired on the select box only works on the first row added how do you make it work for every row being added.Thanks.
<html>
<body>
<link href="style.css" rel="stylesheet">
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.1/jquery.min.js"></script>
<script src='script.js'></script>
<table id="addProducts" border="1">
<tr>
<td>POI</td>
<td>Quantity</td>
<td>Price</td>
<td>Product</td>
<td>Add Rows?</td>
</tr>
<tr>
<td>1</td>
<td><input size=25 type="text" id="lngbox" readonly=true/></td>
<td><input size=25 type="text" id="price" readonly=true/></td>
<td>
<select name="selRow0" class="products">
<option value="value0">Product 1</option>
<option value="value1">Product 2</option>
</select>
</td>
<td><input type="button" id="delProducts" value="Delete" onclick="deleteRow(this)"/></td>
<td><input type="button" id="addmoreProducts" value="AddMore" onclick="insRow()"/></td>
</tr>
</table>
<div id="shw"></div>
</body>
</html>
$(function () {
$("select.products").on("change", function () {
var selected = $(this).val();
$("#price").val(selected);
})
});
function deleteRow(row)
{
var i = row.parentNode.parentNode.rowIndex;
document.getElementById('addProducts').deleteRow(i);
}
function insRow()
{
var x = document.getElementById('addProducts');
// deep clone the targeted row
var new_row = x.rows[1].cloneNode(true);
// get the total number of rows
var len = x.rows.length;
// set the innerHTML of the first row
new_row.cells[0].innerHTML = len;
// grab the input from the first cell and update its ID and value
var inp1 = new_row.cells[1].getElementsByTagName('input')[0];
inp1.id += len;
inp1.value = '';
// grab the input from the first cell and update its ID and value
var inp2 = new_row.cells[2].getElementsByTagName('input')[0];
inp2.id += len;
inp2.value = '';
// append the new row to the table
x.appendChild(new_row);
}

I've updated your code. This should work now. Look at this jsfiddle:
JS:
$(function () {
$(document).on('change', 'select.products', function(){
var selected = $(this).val();
$(this).parents('tr').find('.price').val(selected);
});
$(document).on('click', '.addProduct', function(){
var ele = $(this).parents('tr').clone();
ele.find('input[type=text]').val('');
$(this).parents('tr').after(ele);
});
$(document).on('click', '.delProduct', function(){
if($(this).parents('table').find('tr').length > 2) {
$(this).parents('tr').remove();
}
});
});
Also I've updated your HTML:
<td><input size=25 type="text" class="lngbox" readonly=true/></td>
<td><input size=25 type="text" class="price" readonly=true/></td>
<td><input type="button" class="delProduct" value="Delete" /></td>
<td><input type="button" class="addProduct" value="AddMore" /></td>

Try this,
$("select.products").on("change", function(){
var selectedValue = $(this).val();
var td = $(this).parent();
(((td).parent()).children()[2].getElementsByTagName("input")[0]).value = selectedValue;
});

Related

Calculate column on row add for all rows

I have developed a code to build out salary costs for a project. The problem is that only the first row is calculating.
I have searched and found a few forums discussing the same problem but every approach/code looks completely different. Also, I have copied whole coding examples from youtube videos/forums to replicate a solution and none seems to work. I know there may be issues with ID/class but being new to coding, everything just confuses me. Help!
<!DOCTYPE html>
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<title></title>
</head>
<body>
<form name='vetCosting'>
<h3> Salaries </h3>
<table ID="salaries">
<tr>
<th>Classification</th>
<th>Hourly rate</th>
<th>Hours</th>
<th>Cost</th>
<th>Comments</th>
<th>Type</th>
<th></th>
<th></th>
</tr>
<tr>
<td>
<select>
<option value="T1.0">Teacher 1.0</option>
<option value="T1.1">Teacher 1.1</option>
<option value="T1.2">Teacher 1.2</option>
<option value="T1.3">Teacher 1.3</option>
</select>
</td>
<td><input type="number" name="hourlyRate" value="" onFocus="startCalc();" onBlur="stopCalc()"></td>
<td><input type="number" name="salaryHours" value="" onFocus="startCalc();" onBlur="stopCalc()"></td>
<td><input type="number" name="salaryCost" readonly="readonly"></td>
<td><input type="text" name="salComments"></td>
<td><input type="text" name="salType"></td>
<td><input type="button" value="+" ; onclick="ob_adRows.addRow(this)"></td>
<td><input type="button" value="-" ; onclick="ob_adRows.delRow(this)"></td>
</tr>
</table>
</form>
<script>
function startCalc() {
interval = setInterval("calc()", 2);
}
function calc() {
hrRate = document.vetCosting.hourlyRate.value;
salHours = document.vetCosting.salaryHours.value;
document.vetCosting.salaryCost.value = ((hrRate * 1) * (salHours * 1));
}
function stopCalc() {
clearInterval(interval);
}
</script>
<script>
function adRowsTable(id) {
var table = document.getElementById(id);
var me = this;
if (document.getElementById(id)) {
var row1 = table.rows[1].outerHTML;
function setIds() {
var tbl_id = document.querySelectorAll('#' + id + ' .tbl_id');
for (var i = 0; i < tbl_id.length; i++) tbl_id[i].innerHTML = i + 1;
}
me.addRow = function (btn) {
btn ? btn.parentNode.parentNode.insertAdjacentHTML('afterend', row1) :
table.insertAdjacentHTML('beforeend', row1);
setIds();
}
me.delRow = function (btn) {
btn.parentNode.parentNode.outerHTML = '';
setIds();
}
}
}
var ob_adRows = new adRowsTable('salaries');
</script>
</body>
</html>
I would like to be able to add and remove rows with calculations computing correctly for every row based on data inputs.
My first step would be to change your code from using setInterval() because that is running every 2 milliseconds even when there is no change in the input and the user is simply sitting there. I'd change it to a onKeyUp event that fires much less frequently.
That's done by simply changing your inputs to this:
<td><input type="number" name="hourlyRate" value="" onKeyUp="calc();"></td>
So we get rid of the startCalc() and stopCalc() functions.
Now, once we have multiple rows, we need a way to identify each row. So we give your first row an id of 'row_0' and also pass it through your calc() functions as follows:
<td><input type="number" name="hourlyRate" value="" onKeyUp="calc('row_0');"></td>
We then update your calc() method to this, so that it can use each row individually:
function calc(id) {
var row = document.getElementById(id);
var hrRate = row.querySelector('input[name=hourlyRate]').value;
var salHours = row.querySelector('input[name=salaryHours]').value;
row.querySelector('input[name=salaryCost]').value = ((hrRate * 1) * (salHours * 1));
}
Next, upon clicking the buttons, this error is fired:
Uncaught ReferenceError: ob_adRows is not defined at HTMLInputElement.onclick
To change this, we'll change the function that you've written. Let's first prepare a template for each row, and then simply append it to the innerHTML of the table. However, this won't work because it will also refresh the entire table, hence wiping out data from our existing rows too. So we use this to make a new HTML node with of a row with the id 'row_x':
function newRowTemplate(rowCount) {
var temp = document.createElement('table');
temp.innerHTML = `<tr id='row_${rowCount}'>
<td>
<select>
<option value="T1.0">Teacher 1.0</option>
<option value="T1.1">Teacher 1.1</option>
<option value="T1.2">Teacher 1.2</option>
<option value="T1.3">Teacher 1.3</option>
</select>
</td>
<td><input type="number" name="hourlyRate" value="" onKeyUp="calc('row_${rowCount}');"></td>
<td><input type="number" name="salaryHours" value="" onkeyUp = "calc('row_${rowCount}');"></td>
<td><input type="number" name="salaryCost" readonly="readonly"></td>
<td><input type="text" name="salComments"></td>
<td><input type="text" name="salType"></td>
<td><input type="button" value="+" ; onclick="addRow()"></td>
<td><input type="button" value="-" ; onclick="removeRow(this)"></td>
</tr>`;
return temp.firstChild;
}
We directly make our new functions:
function addRow() {
var newRow = newRowTemplate(rowCount);
table.appendChild(newRow);
rowCount += 1;
}
function removeRow(el) {
el.parentNode.parentNode.remove();
rowCount -= 1;
}
And finally, we use these new functions in our original elements as follows:
<td><input type="button" value="+" ; onclick="addRow()"></td>
<td><input type="button" value="-" ; onclick="removeRow(this)"></td>
Here's the final result:
function calc(id) {
var row = document.getElementById(id);
var hrRate = row.querySelector('input[name=hourlyRate]').value;
var salHours = row.querySelector('input[name=salaryHours]').value;
row.querySelector('input[name=salaryCost]').value = ((hrRate * 1) * (salHours * 1));
}
var table = document.getElementById('salaries');
var rowCount = 1;
function newRowTemplate(rowCount) {
var temp = document.createElement('table');
temp.innerHTML = `<tr id='row_${rowCount}'>
<td>
<select>
<option value="T1.0">Teacher 1.0</option>
<option value="T1.1">Teacher 1.1</option>
<option value="T1.2">Teacher 1.2</option>
<option value="T1.3">Teacher 1.3</option>
</select>
</td>
<td><input type="number" name="hourlyRate" value="" onKeyUp="calc('row_${rowCount}');"></td>
<td><input type="number" name="salaryHours" value="" onkeyUp = "calc('row_${rowCount}');"></td>
<td><input type="number" name="salaryCost" readonly="readonly"></td>
<td><input type="text" name="salComments"></td>
<td><input type="text" name="salType"></td>
<td><input type="button" value="+" ; onclick="addRow()"></td>
<td><input type="button" value="-" ; onclick="removeRow(this)"></td>
</tr>`;
return temp.firstChild;
}
function addRow() {
var newRow = newRowTemplate(rowCount);
table.appendChild(newRow);
rowCount += 1;
}
function removeRow(el) {
el.parentNode.parentNode.remove();
rowCount -= 1;
}
<body>
<form name="vetCosting">
<h3> Salaries </h3>
<h3> Salaries </h3>
<table id="salaries">
<tr>
<th>Classification</th>
<th>Hourly rate</th>
<th>Hours</th>
<th>Cost</th>
<th>Comments</th>
<th>Type</th>
<th></th>
<th></th>
</tr>
<tr id="row_0">
<td>
<select>
<option value="T1.0">Teacher 1.0</option>
<option value="T1.1">Teacher 1.1</option>
<option value="T1.2">Teacher 1.2</option>
<option value="T1.3">Teacher 1.3</option>
</select>
</td>
<td><input type="number" name="hourlyRate" value="" onKeyUp="calc('row_0');"></td>
<td><input type="number" name="salaryHours" value="" onkeyUp="calc('row_0');"></td>
<td><input type="number" name="salaryCost" readonly="readonly"></td>
<td><input type="text" name="salComments"></td>
<td><input type="text" name="salType"></td>
<td><input type="button" value="+" ; onclick="addRow()"></td>
<td><input type="button" value="-" ; onclick="removeRow(this)"></td>
</tr>
</table>
</form>
</body>
I just realized a bug in my code. Once row_x is created, and I delete and add another row, it'll create row_x again because the rowCount returns to x. You can fix this by removing the decrement in the remove row function.

Using JavaScript to add new row to table but how to I set the variables to be unique if I clone?

I have a button that the user clicks on to add a new row to the bottom of an input table. I would like this to also increment the id. So the next row would have desc2, hours2, rate2 and amount2 as the id. Is there a way to do this in the JavaScript function.
Also - just want to check my logic on this. After the user completes the filled out form, I will be writing all the data to a mysql database on two different tables. Is this the best way to go about this? I want the user to be able to add as many lines in the desc_table as they need. If this is the correct way to be going about this, what is the best way to determine how many lines they have added so I can insert into the db table using a while loop?
JS file:
function new_line() {
var t = document.getElementById("desc_table");
var rows = t.getElementsByTagName("tr");
var r = rows[rows.length - 1];
var x = rows[1].cloneNode(true);
x.style.display = "";
r.parentNode.insertBefore(x, r);
}
HTML:
<table id="desc_table">
<tr>
<td><font><br><h3>Description</h3></font></td>
<td><font><h3>Hours</h3></font></td>
<td><font><h3>Rate</h3></font></td>
<td><font><h3>Amount</h3></font></td>
<td></td>
</tr>
<tr>
<td ><textarea name="description" id="desc1" ></textarea></td>
<td> <input type="text" name="hours" id="hours1" ></td>
<td> <input type="text" name="rate" id="rate1"></td>
<td><input type="text" name="amount" id="amount1"></td>
<td>
<button type="button" name="add_btn" onclick="new_line(this)">+</button>
<button type="button" name="delete_btn" onclick="delete_row(this)">x</button>
</td>
</tr>
</table>
Thank you!
Check this code.After appending the row it counts the number of rows and and then assigns via if condition and incremental procedure the id's:
function new_line() {
var t = document.getElementById("desc_table");
var rows = t.getElementsByTagName("tr");
var r = rows[rows.length - 1];
var x = rows[1].cloneNode(true);
x.style.display = "";
r.parentNode.insertBefore(x, r);
for(var i=1;i<rows.length;i++){
if(rows[i].children["0"].children["0"].id.match((/desc/g))){
rows[i].children["0"].children["0"].id='desc'+i;
}
if(rows[i].children["1"].children["0"].id.match((/hours/g))){
rows[i].children["1"].children["0"].id='hours'+i;
}
if(rows[i].children["2"].children["0"].id.match((/rate/g))){
rows[i].children["2"].children["0"].id='rate'+i;
}
if(rows[i].children["3"].children["0"].id.match((/amount/g))){
rows[i].children["3"].children["0"].id='amount'+i;
}
}
}
<table id="desc_table">
<tr>
<td><font><br><h3>Description</h3></font></td>
<td><font><h3>Hours</h3></font></td>
<td><font><h3>Rate</h3></font></td>
<td><font><h3>Amount</h3></font></td>
<td></td>
</tr>
<tr>
<td ><textarea name="description" id="desc1" ></textarea></td>
<td> <input type="text" name="hours" id="hours1" ></td>
<td> <input type="text" name="rate" id="rate1"></td>
<td><input type="text" name="amount" id="amount1"></td>
<td>
<button type="button" name="add_btn" onclick="new_line(this)">+</button>
<button type="button" name="delete_btn" onclick="delete_row(this)">x</button>
</td>
</tr>
</table>
Please change variable names for more descriptive. :)
Example solution...
https://jsfiddle.net/Platonow/07ckv5u7/1/
function new_line() {
var table = document.getElementById("desc_table");
var rows = table.getElementsByTagName("tr");
var row = rows[rows.length - 1];
var newRow = rows[rows.length - 1].cloneNode(true);
var inputs = newRow.getElementsByTagName("input");
for(let i=0; i<inputs.length; i++) {
inputs[i].id = inputs[i].name + rows.length;
}
var textarea = newRow.getElementsByTagName("textarea")[0];
textarea.id = textarea.name + rows.length;
table.appendChild(newRow);
}
Note that I removed/edited below fragment.
x.style.display = "";
r.parentNode.insertBefore(x, r);
You could do this a lot easier with jquery or another dom manipulation language, but with vanilla JS here's an example of simply looping through the new row's inputs & textarea and incrementing a counter to append.
var count = 1;
function new_line() {
count++;
var t = document.getElementById("desc_table");
var rows = t.getElementsByTagName("tr");
var r = rows[rows.length - 1];
var x = rows[1].cloneNode(true);
x.style.display = "";
r.parentNode.insertBefore(x, r);
// update input ids
var newInputs = Array.from(x.getElementsByTagName('input'))
.concat(Array.from(x.getElementsByTagName('textarea')));
newInputs.forEach(function(input) {
var id = input.getAttribute('id').replace(/[0-9].*/, '');
input.setAttribute('id', id + count);
});
}
<table id="desc_table">
<tr>
<td><font><br><h3>Description</h3></font></td>
<td><font><h3>Hours</h3></font></td>
<td><font><h3>Rate</h3></font></td>
<td><font><h3>Amount</h3></font></td>
<td></td>
</tr>
<tr>
<td ><textarea name="description" id="desc1" ></textarea></td>
<td> <input type="text" name="hours" id="hours1" ></td>
<td> <input type="text" name="rate" id="rate1"></td>
<td><input type="text" name="amount" id="amount1"></td>
<td>
<button type="button" name="add_btn" onclick="new_line(this)">+</button>
<button type="button" name="delete_btn" onclick="delete_row(this)">x</button>
</td>
</tr>
</table>

oninput event in html works fine till <form></form> is added?

I am adding rows in table and deleting, this works fine. using oninput="" event i am also able to calculate the total cost by calling javascript function.
Now, the moment i add <form></form>, neither am able to add rows nor moving any forward. I am new to javascript, and have no clue what is going on. please help somebody.
<div class="container">
<p>Add and Delete Items with Total Cost Value</p>
<form>
<div id="tableDiv">
<table id="myTableHead">
<tr>
<th>Item Name</th>
<th>Item Cost</th>
</tr>
<tr>
<td><input type="text" name="ItemName[]" id="ItemName" /></td>
<td><input class="ItemCostClass" type="number" name="ItemCost[]" oninput="myTotalFunction()" id="ItemCost" /></td>
</tr>
</table>
<table id="myTable">
</table>
<table id="myTableTot">
<tr>
<td><input type="text" name="Total" value="Total Cost Value --->" readonly /></td>
<td><input type="number" name="TotalValue" id="TotalValue" value=0 readonly /></td>
</tr>
</table>
</div>
<br>
<button onclick="myCreateFunction()">Create row</button>
<button onclick="myDeleteFunction()">Delete row</button>
</form>
</div>
<script>
function myCreateFunction() {
var TotalCostValueCurrent = parseFloat(document.getElementById("TotalValue").value);
if (TotalCostValueCurrent <= 25000) {
var table = document.getElementById("myTable");
var row = table.insertRow(-1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = '<input type="text" name="ItemName[]" id="childItemName" />';
cell2.innerHTML = '<input class="ItemCostClass" type="number" name="ItemCost[]" oninput="myTotalFunction()" id="childItemCost" />';
} else {
window.alert("Sorry, You Have Reached Max Shipping Value Limit of 25000, please reduce Pieces to Max Value of 25000");
}
}
function myTotalFunction() {
var arrItemCost = document.getElementById("tableDiv").getElementsByClassName("ItemCostClass");
var arrLen = arrItemCost.length;
var i = 0;
var itemCostSum = 0;
while (i <= arrLen && itemCostSum <= 25000) {
if (itemCostSum <= 25000) {
itemCostSum = itemCostSum + parseFloat(arrItemCost[i].value);
i++;
document.getElementById("TotalValue").value = Math.ceil(itemCostSum); // Update Total Value
}
}
}
function myDeleteFunction() {
var arrItemCost = document.getElementById("tableDiv").getElementsByClassName("ItemCostClass");
var arrLen = arrItemCost.length;
var TotalValueCurrent = parseFloat(document.getElementById("TotalValue").value);
var itemCostFinal = 0;
itemCostFinal = TotalValueCurrent - parseInt(arrItemCost[arrLen-1].value);
//FINAL OUTPUT
document.getElementById("myTable").deleteRow(-1); // Delete Last Row
document.getElementById("TotalValue").value = Math.ceil(itemCostFinal); // Final Cost Value
document.getElementById("tableDiv").getElementsByClassName("ItemCostClass").pop(); // Drop last value of Item Array
}
</script>
Inside the form tags buttons tend to do the default action which is submit.
So change your button from,
<button onclick="myCreateFunction()">Create row</button>
<button onclick="myDeleteFunction()">Delete row</button>
to
<input type="button" onclick="myCreateFunction()" value="Create row">
<input type="button" onclick="myDeleteFunction()" value ="Delete row">
You have to add Input tag instead of button tag. Because button tag in form specifies default submit event on-click so your form submitted when you add any row and also refresh.
<div class="container">
<p>Add and Delete Items with Total Cost Value</p>
<form>
<div id="tableDiv">
<table id="myTableHead">
<tr>
<th>Item Name</th>
<th>Item Cost</th>
</tr>
<tr>
<td><input type="text" name="ItemName[]" id="ItemName" /></td>
<td><input class="ItemCostClass" type="number" name="ItemCost[]" oninput="myTotalFunction()" id="ItemCost" /></td>
</tr>
</table>
<table id="myTable">
</table>
<table id="myTableTot">
<tr>
<td><input type="text" name="Total" value="Total Cost Value --->" readonly /></td>
<td><input type="number" name="TotalValue" id="TotalValue" value=0 readonly /></td>
</tr>
</table>
</div>
<br>
<input type="button" onclick="myCreateFunction()" value="Create row" />
<input type="button" onclick="myDeleteFunction()" value="Delete row" />
</form>
</div>
<script>
function myCreateFunction() {
var TotalCostValueCurrent = parseFloat(document.getElementById("TotalValue").value);
if (TotalCostValueCurrent <= 25000) {
var table = document.getElementById("myTable");
var row = table.insertRow(-1);
var cell1 = row.insertCell(0);
var cell2 = row.insertCell(1);
cell1.innerHTML = '<input type="text" name="ItemName[]" id="childItemName" />';
cell2.innerHTML = '<input class="ItemCostClass" type="number" name="ItemCost[]" oninput="myTotalFunction()" id="childItemCost" />';
} else {
window.alert("Sorry, You Have Reached Max Shipping Value Limit of 25000, please reduce Pieces to Max Value of 25000");
}
}
function myTotalFunction() {
var arrItemCost = document.getElementById("tableDiv").getElementsByClassName("ItemCostClass");
var arrLen = arrItemCost.length;
var i = 0;
var itemCostSum = 0;
while (i < arrLen && itemCostSum <= 25000) {
if (itemCostSum <= 25000) {
itemCostSum = itemCostSum + parseFloat(arrItemCost[i].value);
i++;
document.getElementById("TotalValue").value = Math.ceil(itemCostSum); // Update Total Value
}
}
}
function myDeleteFunction() {
var arrItemCost = document.getElementById("tableDiv").getElementsByClassName("ItemCostClass");
var arrLen = arrItemCost.length;
var TotalValueCurrent = parseFloat(document.getElementById("TotalValue").value);
var itemCostFinal = 0;
itemCostFinal = TotalValueCurrent - parseInt(arrItemCost[arrLen-1].value);
//FINAL OUTPUT
document.getElementById("myTable").deleteRow(-1); // Delete Last Row
document.getElementById("TotalValue").value = Math.ceil(itemCostFinal); // Final Cost Value
document.getElementById("tableDiv").getElementsByClassName("ItemCostClass").pop(); // Drop last value of Item Array
}
</script>

How to edit and delete the row in Javascript?

When I click table row, that row value will display the below text box, then I click + button to copy the first row values and insert new row and place value correctly.
When I click edit button # that value again place to first row. How to find that row index. How to get the particular ID?
<script>
function insRow()
{
var x=document.getElementById('scrolltable');
var new_row = x.rows[1].cloneNode(true);
var len = x.rows.length;
var code=document.getElementById('code').value;
var product=document.getElementById('product_name').value;
var qty=document.getElementById('quantity').value;
var rate=document.getElementById('amount').value;
var amount=document.getElementById('total').value;
var inp1 = new_row.cells[0].getElementsByTagName('input')[0];
inp1.id += len;
inp1.value = code;
var inp2 = new_row.cells[1].getElementsByTagName('input')[0];
inp2.id += len;
inp2.value = product;
var inp3 = new_row.cells[2].getElementsByTagName('input')[0];
inp3.id += len;
inp3.value = qty;
var inp4 = new_row.cells[3].getElementsByTagName('input')[0];
inp4.id += len;
inp4.value = rate;
var inp5 = new_row.cells[4].getElementsByTagName('input')[0];
inp5.id += len;
inp5.value = amount;
var button = new_row.cells[5].getElementsByTagName('input')[0];
button.value = "#";
button.onclick = function(it) {editRow(it)};
//cell4.appendChild(inp4);
x.appendChild( new_row );
document.getElementById('code').value='';
document.getElementById('product_name').value='';
document.getElementById('quantity').value='';
document.getElementById('amount').value='';
document.getElementById('total').value='';
document.getElementById('code').focus();
}
function deleteRow(row)
{
r=row.parentNode.parentNode;
r.parentNode.removeChild(r);
}
function editRow(evt) {
var x=document.getElementById('scrolltable');
//var l1 = evt.target.parentNode.parentNode;
//alert(l1);
var errorList = "";
var l=x.rows.length;
//var l=x.rowsIndex;
var y=l-1;
alert(l);
//alert("code"+y);
var code=document.getElementById('code'+y).value;
var product=document.getElementById('product_name'+y).value;
var qty=document.getElementById('quantity'+y).value;
var rate=document.getElementById('amount'+y).value;
var amount=document.getElementById('total'+y).value;
document.getElementById('code').value=code;
document.getElementById('product_name').value=product;
document.getElementById('quantity').value=qty;
document.getElementById('amount').value=rate;
document.getElementById('total').value=amount;
var i = evt.target.parentNode.parentNode.rowIndex;
document.getElementById('scrolltable').deleteRow(i);
}
</script>
My HTML code is:
<table class="table table-striped table-bordered dTableR" id="scrolltable">
<thead>
<tr>
<th width="10%">Code</th>
<th width="40%">Product</th>
<th width="10%">Total Qty</th>
<th width="10%">Rate</th>
<th width="12%">Amount</th>
<th width="10%">Action</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" name="code" class="span10" id="code" /></td>
<td><input type="text" name="product_name" class="span12" id="product_name" /></td>
<td><input type="text" name="quantity" class="span10" onBlur="calculate(this.value)" id="quantity" maxlength="8"/></td>
<td><input type="text" name="amount_name" class="span10" id="amount" /></td>
<td><input type="text" name="total_name" class="span10" id="total" maxlength="8" /></td>
<td><input type="button" id="addmorePOIbutton" style="width:25px;" value="+" onClick="insRow()"/>
<input type="button" id="delPOIbutton" style="width:25px;" value="-" onClick="deleteRow(this)"/></td>
</tr>
</tbody>
You can use jQuery for edit function :
First change
button.onclick = function(it) {editRow(it)};
to
button.onclick = function() {editRow(this)};
and change below function
function editRow(evt)
{
var $tr = $(evt).parents('tr'); // get parent tr
// put all values in top row
$('#code').val($tr.find('input[id^=code]').val());
$('#product_name').val($tr.find('input[id^=product_name]').val());
$('#quantity').val($tr.find('input[id^=quantity]').val());
$('#amount').val($tr.find('input[id^=amount]').val());
$('#total').val($tr.find('input[id^=total]').val());
// remove clicked tr
$tr.remove();
}
Working jsfiddle
Note : Please add jQuery js file to your html page.
since you are using jquery(as you have tagged this question with jquery), you can use index() function form jquery (http://api.jquery.com/index/).
Here is an updated (http://jsfiddle.net/6yXMF/) jsfiddle.
Which alerts index of the tr from which the input button is clicked.
Currently there are some issues in insertion and deletion or rows in your code. After resolving the issues you just can use the index function as demoed in
insRow() function.
Let me know if you have any queries.

add/remove multiple rows using checkbox with JQUERY

I have snippet in javascript that add/remove multiple rows within a table. I would like to implement the same thing into JQUERY. At the moment, the checkboxes does'nt work, but I would like them to work for the sake of userbility. I got no clue on jquery at moment. Would you help on the implementation.
Fiddle:http://jsfiddle.net/ronn_nasso/qN2Z8/
<HEAD>
<TITLE> Add/Remove dynamic rows in HTML table </TITLE>
<link rel="stylesheet" type="text/css" href="addRemove.css"/>
<script language="JavaScript" type="text/javascript">
function hasClass(el, cssClass) {
return el.className && new RegExp("(^|\\s)" + cssClass + "(\\s|$)").test(el.className);
}
var rowNumber = 1;
function addRow(tableID) {
var counter = document.getElementById(tableID).rows.length-1;
var row = document.getElementById(tableID);
var newRow0 = row.rows[1].cloneNode(true);
var newRow1 = row.rows[counter].cloneNode(true);
// Increment
rowNumber ++;
newRow0.getElementsByTagName('td')[1].innerHTML = rowNumber;
// Update the child Names
var items = newRow0.getElementsByTagName("input");
for (var i = 0; i < items.length; i++) {
items[i].value = null;
items[i].name = counter + '_' + items[i].name;
}
var refRow = row.getElementsByTagName('tbody')[0];
refRow.insertBefore(newRow0, refRow.nextSibling);
refRow.insertBefore(newRow1, refRow.nextSibling);
}
function deleteRow(tableID) {
var table = document.getElementById(tableID);
var i = table.rows.length - 1;
while (2 < i && !hasClass(table.rows[i], 'row-parent')) {
table.deleteRow(i)
i--;
}
if (2 < i) {
table.deleteRow(i)
rowNumber --;
}
}
function addChildRow(e, tableID) {
var table = document.getElementById(tableID);
var newRow = table.rows[0].cloneNode(true);
// Increment
if (e > 0)
if (!isNaN(table.rows[e-1].getElementsByTagName('td')[4].innerHTML))
var counter = parseInt(table.rows[e-1].getElementsByTagName('td')[4].innerHTML)
else
var counter = parseInt(table.rows[e-1].getElementsByTagName('td')[1].innerHTML)
newRow.getElementsByTagName('td')[1].innerHTML = counter + 1;
// Update the child Names
var items = newRow.getElementsByTagName("input");
for (var i = 0; i < items.length; i++) {
items[i].value = null;
items[i].name = counter + '_' + items[i].name;
}
var i = e;
while (1 <= i && !hasClass(table.rows[i], 'row-parent'))
i--;
var parent = table.rows[i].getElementsByTagName('td');
parent[0].rowSpan = counter+2;
parent[1].rowSpan = counter+2;
parent[2].rowSpan = counter+2;
var refRow = table.getElementsByTagName('tr')[e-1];
refRow.parentNode.insertBefore(newRow, refRow.nextSibling);
}
function deleteChildRow(e, tableID) {
var table = document.getElementById(tableID);
var i = e;
while (1 <= i && !hasClass(table.rows[i], 'row-parent'))
i--;
if (e-1 > i)
table.deleteRow(e-1)
}
</script>
</HEAD>
<BODY>
<form action="Untitled-2.php" name="dataTable" method="post">
<table width="760" id="dataTable" border="1">
<tr>
<td width="20">
<input type="checkbox" name="chk1" />
</td>
<td width="12">1</td>
<td width="200">
<input type="text" name="txtbox1[]" />
</td>
<td width="146">
<input type="text" name="txtbox2[]" />
</td>
<td width="188">
<input type="text" name="txtbox3[]" />
</td>
</tr>
<tr class="row-parent">
<td width="22" rowspan="2">
<input type="checkbox" name="chk" />
</td>
<td width="12" rowspan="2">1</td>
<td width="149" rowspan="2">
<input type="text" name="txtbox[]" />
</td>
<td width="20">
<input type="checkbox" name="chk1" />
</td>
<td width="12">1</td>
<td width="200">
<input type="text" name="txtbox1[]" />
</td>
<td width="146">
<input type="text" name="txtbox2[]" />
</td>
<td width="188">
<input type="text" name="txtbox3[]" />
</td>
</tr>
<tr>
<td width="20"> </td>
<td width="12"> </td>
<td>
<input type="button" value="Add Row" onClick="addChildRow(this.parentNode.parentNode.rowIndex, 'dataTable')" />
<input type="button" value="Delete Row" onClick="deleteChildRow(this.parentNode.parentNode.rowIndex, 'dataTable')" />
</td>
<td width="146"> </td>
<td width="188"> </td>
</tr>
</table>
<input type="button" value="Add Row" onClick="addRow('dataTable')" />
<input type="button" value="Delete Row" onClick="deleteRow('dataTable')" />
</form>
</BODY>
</HTML>
Fiddle:http://jsfiddle.net/ronn_nasso/qN2Z8/
$("#ADD").click(function(){
$("table").append($("tr:last").clone(true));
//clone the last row and add it to table
$("tr:last input").val("");
//reset all the inputs in the last row
});
$("#DEL").click(function(){
$("table tr input:checked").parents('tr').remove();
//find the rows with checked check boxes in them and remove them
});
SAMPLE
updated your code to this:
$("#btnAddRow").on("click",function(){
addRow('dataTable');
});
$("#btnDelRow").on("click",function(){
deleteRow('dataTable');
});
$("#btnAddChildRow").on("click",function(){
var index = $(this).closest('tr').index();
addChildRow(index,'dataTable');
});
$("#btnDelChildRow").on("click",function(){
var index = $(this).closest('tr').index();
deleteChildRow(index,'dataTable');
});
working fiddle here: http://jsfiddle.net/qN2Z8/5/ (check this fiddle)
i hope it helps.
Try following code
<input type="button" id="addPOIbutton" value="Add POIs"/><br/><br/>
<table id="POITable" border="1">
<tr>
<td>1</td>
<td><input type="checkbox" id="chck"/></td>
<td><input size=25 type="text" id="latbox"/></td>
<td><input size=25 type="text" id="lngbox" readonly=true/></td>
<td><input type="button" id="delPOIbutton" value="Delete Row" onclick="deleteRow(this)"/></td>
<td><input type="button" id="addmorePOIbutton" value="Add Row" onclick="insRow()"/></td>
</tr>
</table>
<script>
function deleteRow(row)
{
var i=row.parentNode.parentNode.rowIndex;
document.getElementById('POITable').deleteRow(i);
}
function insRow()
{
var x=document.getElementById('POITable');
var new_row = x.rows[0].cloneNode(true);
var len = x.rows.length;
new_row.cells[0].innerHTML = len;
var inp1 = new_row.cells[1].getElementsByTagName('input')[0];
inp1.id += len;
inp1.value = '';
var inp2 = new_row.cells[2].getElementsByTagName('input')[0];
inp2.id += len;
inp2.value = '';
x.appendChild( new_row );
}
</script>
Link to fiddle here

Categories