Reset(Undo) the add table row action JQUERY - javascript

Each time the button is clicked, table row(s) will be added depends on user input. Im wondering what if user makes a mistake or change his mind, is there any way to reset(undo) the add table row action. Thanks in advance
$('#add-row').click(function() {
var $tbody, $row, additionalRows;
var numNewRows = parseInt($('#insert-rows-amnt').val(), 10);
if (isNaN(numNewRows) || numNewRows <= 0) {
alert('Please enter number of injection');
} else {
$tbody = $('table#one tbody ');
$row = $tbody.find('tr:last');
var lastRowIndex=($row.index()==-1? 0:$row.index()) +1 ;
additionalRows = new Array(numNewRows);
for(i=0;i<numNewRows;i++)
{
additionalRows[i]=` <tr>
<td>${lastRowIndex}</td>
<td>
<input type="text" style="width: 100px" name="vaccineid[]"></td>
<td><input type="text" style="width:160px"name="vaccinename1[]"> </td>
</tr>`
lastRowIndex=lastRowIndex+1;
}
$tbody.append(additionalRows.join());
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="insert-rows-amnt" name="insert-rows-amnt" value="<?php echo $tam ?>" />
<button id="add-row" type="button">Add</button>
<button type="reset" name="reset" >Reset</button>
<table id="one">
<tbody>
</tbody>
</table>

you can use remove() on reset button click to remove the rows added.
$('#add-row').click(function() {
var $tbody, $row, additionalRows;
var numNewRows = parseInt($('#insert-rows-amnt').val(), 10);
if (isNaN(numNewRows) || numNewRows <= 0) {
alert('Please enter number of injection');
} else {
$tbody = $('table#one tbody ');
$row = $tbody.find('tr:last');
var lastRowIndex=($row.index()==-1? 0:$row.index()) +1 ;
additionalRows = new Array(numNewRows);
for(i=0;i<numNewRows;i++)
{
additionalRows[i]=` <tr>
<td>${lastRowIndex}</td>
<td>
<input type="text" style="width: 100px" name="vaccineid[]"></td>
<td><input type="text" style="width:160px"name="vaccinename1[]"> </td>
</tr>`
lastRowIndex=lastRowIndex+1;
}
$tbody.append(additionalRows.join());
}
});
$('[name="reset"]').click(function() {
$('#one tr').remove();
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="insert-rows-amnt" name="insert-rows-amnt" value="<?php echo $tam ?>" />
<button id="add-row" type="button">Add</button>
<button type="reset" name="reset" >Reset</button>
<table id="one">
<tbody>
</tbody>
</table>

Here you go with the solution https://jsfiddle.net/t14mszuc/1/
$('#add-row').click(function() {
var $tbody, $row, additionalRows;
var numNewRows = parseInt($('#insert-rows-amnt').val(), 10);
$('button[type="reset"]').attr('lastCount', parseInt($('#insert-rows-amnt').val(), 10));
if (isNaN(numNewRows) || numNewRows <= 0) {
alert('Please enter number of injection');
} else {
$tbody = $('table#one tbody ');
$row = $tbody.find('tr:last');
var lastRowIndex=($row.index()==-1? 0:$row.index()) +1 ;
additionalRows = new Array(numNewRows);
for(i=0;i<numNewRows;i++)
{
additionalRows[i]=` <tr>
<td>${lastRowIndex}</td>
<td>
<input type="text" style="width: 100px" name="vaccineid[]"></td>
<td><input type="text" style="width:160px"name="vaccinename1[]"> </td>
</tr>`
lastRowIndex=lastRowIndex+1;
}
$tbody.append(additionalRows.join());
}
});
$('button[type="reset"]').click(function(){
var cnt = $('button[type="reset"]').attr('lastCount');
for(var i=0; i<cnt; i++){
$('table tbody tr:nth-last-child(' + (cnt-i) + ')').remove();
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="insert-rows-amnt" name="insert-rows-amnt" value="<?php echo $tam ?>" />
<button id="add-row" type="button">Add</button>
<button type="reset" name="reset" >Reset</button>
<table id="one">
<tbody>
</tbody>
</table>
Solution explain
It will remove the last inserted rows not the entire rows (it's like undo)

You can also try for this solution.
$('#add-row').click(function() {
var $tbody, $row, additionalRows;
var numNewRows = parseInt($('#insert-rows-amnt').val(), 10);
if (isNaN(numNewRows) || numNewRows <= 0) {
alert('Please enter number of injection');
} else {
$tbody = $('table#one tbody ');
$row = $tbody.find('tr:last');
var lastRowIndex=($row.index()==-1? 0:$row.index()) +1 ;
additionalRows = new Array(numNewRows);
for(i=0;i<numNewRows;i++)
{
additionalRows[i]=` <tr>
<td>${lastRowIndex}</td>
<td>
<input type="text" style="width: 100px" name="vaccineid[]"></td>
<td><input type="text" style="width:160px"name="vaccinename1[]"> </td>
</tr>`
lastRowIndex=lastRowIndex+1;
}
$tbody.append(additionalRows.join());
}
});
$('#remove-row').click(function() {
var $tbody, $row, additionalRows;
var numNewRows = parseInt($('#remove-rows-amnt').val(), 10);
if (isNaN(numNewRows) || numNewRows <= 0) {
alert('Please enter number of injection');
} else {
$tbody = $('table#one tbody ');
$row = $tbody.find('tr:last');
var lastRowIndex=($row.index()==-1? 0:$row.index()) +1 ;
additionalRows = new Array(numNewRows);
for(i=0;i<numNewRows;i++)
{
$('table tr:last').remove();
}
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="insert-rows-amnt" name="insert-rows-amnt" value="<?php echo $tam ?>" />
<button id="add-row" type="button">Add</button>
<input type="number" id="remove-rows-amnt" name="remove-rows-amnt" value="<?php echo $tam ?>" />
<button id="remove-row" type="button">Remove</button>
<table id="one">
<tbody>
</tbody>
</table>
Thanks!

Related

how can I get this code to calculate just the amount column

I cannot figure out how to make this code just calculate the amount column the addrow and deleterow functions work just can figure out who to get this to calculate the total amount on the amount column.
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(document).on('click', '#ncItems.add', function() {
var row = $(this).parents('tr');
var clone = row.clone();
// clear the values
var tr = clone.closest('tr');
tr.find('input[type=text]').val('');
$(this).closest('tr').after(clone);
var total = 0;
$(".last").each(function() {
if (!$(this).val() == '') {
total = total + parseFloat($(this).val());
}
})
$("#nctotalPrice").html("$" + total +".00");
});
$(document).on("blur", ".last", function() {
var total = 0;
$(".last").each(function() {
if (!$(this).val() == '') {
total = total + parseFloat($(this).val());
}
})
$("#nctotalPrice").html("$" +total+".00");
document.getElementById("ntotal").value ="$" +total+".00";
});
$(document).on('focus', ".last", function() {
var $qty = $(this).parents("tr").find("input[name^='quantity']");
var $pr = $(this).parents("tr").find("input[name^='price']");
var $amnt = $(this).parents("tr").find("input[name^='amount']");
var a = 0;
if ($qty.val() == '' || $pr.val() == '') {
console.log("No values found.");
return false;
} else {
console.log("Converting: ", $qty.val(), $pr.val());
var q = parseInt($qty.val());
var p = parseFloat($pr.val());
console.log("Values found: ", q, p);
}
a = q * p;
$amnt.val(Math.round(a * 100) / 100);
});
$(document).on('click', 'ncItems .removeRow', function() {
if ($('#ncItems .add').length > 1) {
$(this).closest('tr').remove();
}
});
});
</script>
<div id="dvncc">
<form id="ncc">
<table id="ncItems" name="ncItems" align="center">
<tr>
<th>Type</th>
<th>Discription</th>
<th>Amount</th>
<th>Actions</th>
</tr>
<tr>
<td>
<select name="type[]" class="next" required>
<option value=" selected="selected"">Please Select..</option>
<option value="Code">Code</option>
<option value="Regular">Regular</option>
</select>
</td>
<input type="text" name="discription[]" class="next" required />
</td>
<td>
<input type="text" name="amount[]" class="next last" required readonly/>
</td>
<td>
<input type="button" name="addRow[]" class="add" value='+' />
<input type="button" name="addRow[]" class="removeRow" value='-' />
</td>
</tr>
<tr>
<th>Total :</th>
<td id="nctotalPrice"></td>
</tr>
</table>
</form>
</div>
Please try this:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Final</title>
<script src="https://code.jquery.com/jquery-1.12.4.min.js"></script>
<script type="text/javascript">
$(document).ready(function() {
$(document).on('click', '.add', function() {
var row = $(this).parents('tr');
var clone = row.clone();
// clear the values
var tr = clone.closest('tr');
tr.find('input[type=text]').val('');
$(this).closest('tr').after(clone);
var total = 0;
$(".last").each(function() {
if (!$(this).val() == '') {
total = total + parseFloat($(this).val());
}
})
$("#nctotalPrice").html("$" + total +".00");
});
$(document).on("blur", ".last", function() {
var total = 0;
$(".last").each(function() {
if (!$(this).val() == '') {
total = total + parseFloat($(this).val());
}
})
$("#nctotalPrice").html("$" +total+".00");
document.getElementById("ntotal").value ="$" +total+".00";
});
$(document).on('focus', ".last", function() {
var $qty = $(this).parents("tr").find("input[name^='quantity']");
var $pr = $(this).parents("tr").find("input[name^='price']");
var $amnt = $(this).parents("tr").find("input[name^='amount']");
var a = 0;
if ($qty.val() == '' || $pr.val() == '') {
console.log("No values found.");
return false;
} else {
console.log("Converting: ", $qty.val(), $pr.val());
var q = parseInt($qty.val());
var p = parseFloat($pr.val());
console.log("Values found: ", q, p);
}
a = q * p;
$amnt.val(Math.round(a * 100) / 100);
});
$(document).on('click', '.removeRow', function() {
if ($('#ncItems .add').length > 1) {
$(this).closest('tr').remove();
}
});
});
</script>
</head>
<body>
<div id="dvncc">
<form id="ncc">
<table id="ncItems" name="ncItems" align="center">
<tr>
<th>Type</th>
<th>Discription</th>
<th>Amount</th>
<th>Actions</th>
</tr>
<tr>
<td>
<select name="type" class="next" required>
<option value="" selected="selected">Please Select..</option>
<option value="Code">Code</option>
<option value="Regular">Regular</option>
</select>
</td>
<td>
<input type="text" name="discription" class="next" required />
</td>
<td>
<input type="text" name="amount" class="next last" required/>
</td>
<td>
<input type="button" name="addRow" class="add" value='+' />
<input type="button" name="remove" class="removeRow" value='-' />
</td>
</tr>
<tr>
<th>Total :</th>
<td id="nctotalPrice"></td>
</tr>
</table>
</form>
</div>
</body>
</html>

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>

(CLOSED) When button is clicked, How to Get input values in the 1st table row and display them in the newly added rows

Now, when the ok button is clicked, additional rows will be added below the 1st table row. I'm wondering when the button is clicked,how to get the values from the 1st table row, and add those values to the row(s) newly added (possibly more than 1 row depends on how many row(s) user input.
Desired result
No Tommy Danvers
1 Tommy Danvers
2 Tommy Danvers
3 Tommy Danvers
$('#add-row').click(function() {
var $tbody, $row, additionalRows;
var numNewRows = parseInt($('#insert-rows-amnt').val(), 10);
if (isNaN(numNewRows) || numNewRows <= 0) {
alert('Please enter number of row');
} else {
$tbody = $('table#one tbody ');
$row = $tbody.find('tr:last');
var lastRowIndex = ($row.index() == -1 ? 0 : $row.index()) + 1;
additionalRows = new Array(numNewRows);
for (i = 0; i < numNewRows; i++) {
additionalRows[i] = ` <tr>
<td>${lastRowIndex}</td>
<td>
<input type="text" name="name[]"></td>
<td><input type="text" name="other[]"></td>
</tr>`
lastRowIndex = lastRowIndex + 1;
}
$tbody.append(additionalRows.join());
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="insert-rows-amnt" name="insert-rows-amnt" value="<?php echo $tam ?>" />
<button id="add-row" type="button">OK</button>
<table id="one">
<tbody>
<td>
<input type="text" name="id[]" value="No"></td>
<td><input type="text" name="name[]" value="Tommy"> </td>
<td><input type="text" name="other[]" value="Danver"> </td>
</tbody>
</table>
So i have found this will do what i need , it's likely there's gonna be better answer out there. If u have one, please do share. Thank you
$('#add-row').click(function() {
var $tbody, $row, additionalRows;
var numNewRows = parseInt($('#insert-rows-amnt').val(), 10);
if (isNaN(numNewRows) || numNewRows <= 0) {
alert('Please enter number of row');
} else {
$tbody = $('table#one tbody ');
$row = $tbody.find('tr:last');
var lastRowIndex = ($row.index() == -1 ? 0 : $row.index()) + 1;
additionalRows = new Array(numNewRows);
for (i = 0; i < numNewRows; i++) {
additionalRows[i] = ` <tr>
<td>${lastRowIndex}</td>
<td>
<input type="text" name="name[]" class="tommy"></td>
<td><input type="text" name="other[]" class="danver"></td>
</tr>`
lastRowIndex = lastRowIndex + 1;
}
$tbody.append(additionalRows.join());
}
});
$("#add-row").on('click', function() {
var set = $('#tommy,#danver').val();
if (set) {
$('.tommy,.danver ').val(set);
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="insert-rows-amnt" name="insert-rows-amnt" value="<?php echo $tam ?>" />
<button id="add-row" type="button">OK</button>
<table id="one">
<tbody>
<td>
<input type="text" name="id[]" value="No"></td>
<td><input type="text" name="name[]" value="Tommy" id="tommy"> </td>
<td><input type="text" name="other[]" value="Danver" id="danver"> </td>
</tbody>
</table>
Here you go with the solution https://jsfiddle.net/r3rbkf72/1/
$('#add-row').click(function() {
var $tbody, $row, additionalRows;
var numNewRows = parseInt($('#insert-rows-amnt').val(), 10);
if (isNaN(numNewRows) || numNewRows <= 0) {
alert('Please enter number of row');
} else {
$tbody = $('table#one tbody ');
$row = $tbody.find('tr:last');
var lastRowIndex = ($row.index() == -1 ? 0 : $row.index()) + 1;
additionalRows = new Array(numNewRows);
var name = $('table#one tbody td:eq(1) input[name="name[]"]').val();
var other = $('table#one tbody td:eq(2) input[name="other[]"]').val();
for (i = 0; i < numNewRows; i++) {
additionalRows[i] = `<tr>
<td>${lastRowIndex}</td>
<td>
<input type="text" name="name[]" value=${name}></td>
<td><input type="text" name="other[]" value=${other}></td>
</tr>`
lastRowIndex = lastRowIndex + 1;
}
$tbody.append(additionalRows.join());
}
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="number" id="insert-rows-amnt" name="insert-rows-amnt" value="<?php echo $tam ?>" />
<button id="add-row" type="button">OK</button>
<table id="one">
<tbody>
<td>
<input type="text" name="id[]" value="No"></td>
<td><input type="text" name="name[]" value="Tommy"> </td>
<td><input type="text" name="other[]" value="Danver"> </td>
</tbody>
</table>
Below two lines of code I have added.
var name = $('table#one tbody td:eq(1) input[name="name[]"]').val();
var other = $('table#one tbody td:eq(2) input[name="other[]"]').val();
This will help you to receive the data from the top row textbox.

Clone a row in an HTML table and call JavaScript function with the new row

I have a table which has one row in which I multiply two fields, namely quantity and rate/quantity, to get the product total. I have provided a button to add a new row which basically clones the 1st row. Now I want the cloned row to also have the same product as the 1st row. I have tried the following code:
<!DOCTYPE html>
<html>
<h3 align="center">K J Somaiya College Of Engineering, Vidyavihar, Mumbai-400 077</h3>
<h3 align="center">Department Of Information Technology</h3>
<body>
<script>
function WO1() {
var qty = document.getElementById('qty').value;
var price = document.getElementById('price').value;
answer = (Number(qty) * Number(price)).toFixed(2);
document.getElementById('totalprice').value = answer;
}
function WO2() {
var qty = document.getElementById('qty1').value;
var price = document.getElementById('price1').value;
answer = (Number(qty) * Number(price)).toFixed(2);
document.getElementById('totalprice1').value = answer;
}
function WO3() {
var qty = document.getElementById('qty2').value;
var price = document.getElementById('price2').value;
answer = (Number(qty) * Number(price)).toFixed(2);
document.getElementById('totalprice2').value = answer;
}
</script>
<script>
function validateNumbe()
{
var x=document.getElementById("floor").value;
if (x==null || x=="")
{
alert("Floor must be entered");
return false;
}
}
function validateN()
{
var x=document.getElementById("lab").value;
if (x==null || x=="")
{
alert("Laboratory Name must be entered");
return false;
}
}
function validateNumb()
{
var x=document.getElementById("room").value;
if (x==null || x=="")
{
alert("Room No must be entered");
return false;
}
}
function validateNum()
{
var x=document.getElementById("labi").value;
if (x==null || x=="")
{
alert("Name of Laboratory Incharge must be entered");
return false;
}
}
function validateNu()
{
var x=document.getElementById("year").value;
if (x==null || x=="")
{
alert("Budget for the year must be entered");
return false;
}
}
</script>
<table width="100%" cellspacing="10">
<tr>
<td align="left">Date:<input type="date" name="date"/></td>
<td align="right">Floor: <input type="text" id="floor" onchange="validateNumbe()"
onblur="validateNumbe()"/> </td>
</tr>
<tr>
<td align="left">Laboratory Name: <input type="text" id="lab" onchange="validateN()"
onblur="validateN()"/></td>
<td align="right">Room no: <input type="text" id="room" onchange="validateNumb()"
onblur="validateNumb()"/></td>
</tr>
<tr>
<td align="left">Name of Laboratory Incharge: <input type="text" id="labi"
onchange="validateNum()" onblur="validateNum()"/></td>
<td align="right">Budget for the year: <input type="text" id="year" onchange="validateNu()"
onblur="validateNu()"/></td>
</tr>
</table>
<h3 align="left"><b>Computer</b><h3>
<table id="POITable" border="1" width="100%">
<tr>
<td style="width:10%">Sr No.</td>
<td>Item Description</td>
<td>Quantity</td>
<td>Rate(Inclusive of Taxes)</td>
<td>Total Cost</td>
</tr>
<tr>
<td>1</td>
<td><textarea rows="4" cols="50" name="comp_item"></textarea></td>
<td><input type='text' name='Quantity' id='qty' class="qty" placeholder='Qty' /></td>
<td><input type='text' name='Rate' id='price' class="price" placeholder='Price (£)'
onChange="WO1()" /></td>
<td><input type='text' name='Total' id='totalprice' class="price" placeholder='Total
Price (£)' /></td>
</tr>
</table>
<input type="button" id="addmorePOIbutton" value="Add New Row"/>
<h3 align="left"><b>Equipment</b><h3>
<table id="POITable1" border="1" width="100%">
<tr>
<th style="width:10%">Sr No.</th>
<th>Item Description</th>
<th>Quantity</th>
<th>Rate(Inclusive of Taxes)</th>
<th>Total Cost</th>
</tr>
<tr>
<td>1</td>
<td><textarea rows="4" cols="50" name="comp_item"></textarea></td>
<td><input type='text' name='Quantity' id='qty1' class="qty" placeholder='Qty' /></td>
<td><input type='text' name='Rate' id='price1' class="price" placeholder='Price (£)'
onChange="WO2()" /></td>
<td><input type='text' name='Total' id='totalprice1' class="price" placeholder='Total
Price (£)' /></td>
</tr>
</table>
<input type="button" id="addmorePOIbutton1" value="Add New Row"/>
<h3 align="left"><b>Furniture</b><h3>
<table id="POITable2" border="1" width="100%">
<tr>
<th style="width:10%">Sr No.</th>
<th>Item Description</th>
<th>Quantity</th>
<th>Rate(Inclusive of Taxes)</th>
<th>Total Cost</th>
</tr>
<tr>
<td>1</td>
<td><textarea rows="4" cols="50" name="comp_item"></textarea></td>
<td><input type='text' name='Quantity' id='qty2' class="qty" placeholder='Qty' /></td>
<td><input type='text' name='Rate' id='price2' class="price" placeholder='Price (£)'
onChange="WO3()" /></td>
<td><input type='text' name='Total' id='totalprice2' class="price" placeholder='Total
Price (£)' /></td>
</tr>
</table>
<input type="button" id="addmorePOIbutton2" value="Add New Row"/>
<script>
( function() { // Prevent vars from leaking to the global scope
var formTable = document.getElementById('POITable');
var newRowBtn = document.getElementById('addmorePOIbutton');
newRowBtn.addEventListener('click', insRow, false); //added eventlistener insetad of inline
onclick-attribute.
function insRow() {
var new_row = formTable.rows[1].cloneNode(true),
numTableRows = formTable.rows.length;
// Set the row number in the first cell of the row
new_row.cells[0].innerHTML = numTableRows;
numTableRows=numTableRows - 1;
var inp1 = new_row.cells[1].getElementsByTagName('textarea')[0];
inp1.name += numTableRows;
inp1.value = '';
var inp2 = new_row.cells[2].getElementsByTagName('input')[0];
inp2.name += numTableRows;
inp2.value = '';
var inp3 = new_row.cells[3].getElementsByTagName('input')[0];
inp3.name += numTableRows;
inp3.value = '';
var inp4 = new_row.cells[4].getElementsByTagName('input')[0];
inp4.name += numTableRows;
inp4.value = '';
// Append the new row to the table
formTable.appendChild( new_row );
}
var formTable1 = document.getElementById('POITable1');
var newRowBtn1 = document.getElementById('addmorePOIbutton1');
newRowBtn1.addEventListener('click', insRow1, false); //added eventlistener insetad of inline
onclick-attribute.
function insRow1() {
var new_row = formTable1.rows[1].cloneNode(true),
numTableRows = formTable1.rows.length;
// Set the row number in the first cell of the row
new_row.cells[0].innerHTML = numTableRows;
numTableRows=numTableRows - 1;
var inp1 = new_row.cells[1].getElementsByTagName('textarea')[0];
inp1.name += numTableRows;
inp1.value = '';
var inp2 = new_row.cells[2].getElementsByTagName('input')[0];
inp2.name += numTableRows;
inp2.value = '';
var inp3 = new_row.cells[3].getElementsByTagName('input')[0];
inp3.name += numTableRows;
inp3.value = '';
var inp4 = new_row.cells[4].getElementsByTagName('input')[0];
inp4.name += numTableRows;
inp4.value = '';
// Append the new row to the table
formTable1.appendChild( new_row );
}
var formTable2 = document.getElementById('POITable2');
var newRowBtn2 = document.getElementById('addmorePOIbutton2');
newRowBtn2.addEventListener('click', insRow2, false); //added eventlistener insetad of inline
onclick-attribute.
function insRow2() {
var new_row = formTable2.rows[1].cloneNode(true),
numTableRows = formTable2.rows.length;
// Set the row number in the first cell of the row
new_row.cells[0].innerHTML = numTableRows;
numTableRows=numTableRows - 1;
var inp1 = new_row.cells[1].getElementsByTagName('textarea')[0];
inp1.name += numTableRows;
inp1.value = '';
var inp2 = new_row.cells[2].getElementsByTagName('input')[0];
inp2.name += numTableRows;
inp2.value = '';
var inp3 = new_row.cells[3].getElementsByTagName('input')[0];
inp3.name += numTableRows;
inp3.value = '';
var inp4 = new_row.cells[4].getElementsByTagName('input')[0];
inp4.name += numTableRows;
inp4.value = '';
// Append the new row to the table
formTable2.appendChild( new_row );
}
})();
function myfun()
{
var lun= document.getElementById('POITable').rows.length;
document.getElementsByName("len")[0].value = lun-1;
var lun1= document.getElementById('POITable1').rows.length;
document.getElementsByName("len1")[0].value = lun1-1;
var lun2= document.getElementById('POITable2').rows.length;
document.getElementsByName("len2")[0].value = lun2-1;
}
function myFunction()
{
window.print();
}
</script>
<input type="hidden" name="len" value="1">
<input type="hidden" name="len1" value="1">
<input type="hidden" name="len2" value="1">
<table width="100%">
<tr>
<td><br><br><br></td>
<td><br><br><br></td>
<td><br><br><br></td>
</tr>
<tr>
<td align="left">Signature <br>Lab-In-Charge</td>
<td align="center">Signature<br>Lab Assistant</td>
<td align="right">Signature <br>Head of Department</td>
</tr>
</table>
<br><br><br>
<input type="submit" value="SUBMIT" onclick='this.form.action="archive.php";myfun();'>
<input type="submit" value="SAVE AND CONTINUE LATER"
onclick='this.form.action="myphpformhandler.php";myfun();'>
</form>
<h3 align="center"><button onclick="myFunction()"><h3>Print this page</h3></button></h3>
</body>
</html>
i have created the JSFiddle but the multiplication is not working in it.
http://jsfiddle.net/xkY4Z/2/
Not a perfect solution to your problem but a bit closer Working Fiddle
Done using jQuery
$(document).on('change','input', function () {
var id = $(this).attr('id').split("-");
var answer = (Number($('#qty-' + id[1]).val()) * Number($('#price-' + id[1]).val())).toFixed(2);
$('#totalprice-' + id[1]).val(answer);
});
Update
Working Fiddle with name
Latest
Fiddle with Grand total

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