Save dynamic html form data to table (Laravel 5.2) - javascript

I have created a dynamic form for making an offer and i don't know how to solve the problem saving that data to a database. I'm using Laravel 5.2 and now i need to make a model and controller....can someone help me please?
How to save this into a database table?
I'm open for hints and tips too, maybe it could be done somehow differently?
This is live form
JSFiddle
<div>
<h1>Angebot</h1>
<form method="POST" action="" accept-charset="UTF-8">
<table id="t1">
<tr>
<th><button type="button" class="addRow">Personal hinzufügen</button></th>
<th>Anzahl</th>
<th>Preis pro Stunde</th>
<th>Stunden</th>
<th>Total</th>
</tr>
<tr id="row0" class="item">
<td><select name="personal" class="select"><optgroup label="Personal">
<option selected="true" disabled="true" style="display:none">--auswählen</option>
<option value="koeche">Köche</option>
<option value="barkeeper">Barkeeper</option>
<option value="garderobiere">Garderobiere</option>
<option value="chauffeure">Chauffeure</option>
<option value="oberkellner">Oberkellner</option>
<option value="serviceleitung">Serviceleitung</option>
<option value="hilfskoch">Hilfskoch</option>
<option value="servicekraefte">Servicekräfte</option>
</optgroup>
</select></td>
<td><input name="anzahl" class="qnty amount" value="" type="number" min="0" step="1"/></td>
<td><input name="preisps" class="price amount" value="" /></td>
<td><input name="stunden" class="hours amount" value="" /></td>
<td><input name="total" class="total" value="" readonly="readonly" /></td>
</tr>
</table>
<br />
<table id="t2">
<tr>
<th>Netto =<br></th>
<th><input id="netto" readonly="readonly" name="netto" type="text" value=""></th>
</tr>
<tr>
<td>Steuer 19% =<br></td>
<td><input id="steuer" readonly="readonly" name="steuer" type="text" value=""></td>
</tr>
<tr>
<td>Brutto =<br></td>
<td><input id="brutto" readonly="readonly" name="brutto" type="text" value=""></td>
</tr>
</table>
<br>
<input type="submit" value="Submit">
<input type="reset" value="Reset">
</form>
</div>
and here is the javascript code
// main function when page is opened
$(document).ready(function () {
// function for adding a new row
var r = 0;
if(r<11){
$('.addRow').click(function () {
r++;
$('#t1').append('<tr id="row' + r + '" class="item"><td><select name="personal' + r + '" class="select"><optgroup label="Personal"><option selected="true" disabled="true" style="display:none">--auswählen</option><option value="koeche">Köche</option><option value="barkeeper">Barkeeper</option><option value="garderobiere">Garderobiere</option><option value="chauffeure">Chauffeure</option><option value="oberkellner">Oberkellner</option><option value="serviceleitung">Serviceleitung</option><option value="hilfskoch">Hilfskoch</option><option value="servicekraefte">Servicekräfte</option></optgroup></select></td><td><input name="anzahl' + r + '" class="qnty amount" value="" type="number" min="0" step="1"/></td><td><input name="preisps' + r + '" class="price amount" value="" /></td><td><input name="stunden' + r + '" class="hours amount" value="" /></td><td><input name="total' + r + '" class="total" value="" readonly="readonly" /></td><td><button type="button" name="remove" id="' + r + '" class="btn_remove">X</button></td></tr>');
});
// remove row when X is clicked
$(document).on("click", ".btn_remove", function () {
var button_id = $(this).attr("id");
$("#row" + button_id + '').remove();
});
// calculate everything
$(document).on("keyup", ".amount", calcAll);
}
});
// function for calculating everything
function calcAll(event) {
// calculate total for one row
$(".item").each(function () {
var qnty = 1;
var price = 1;
var hours = 1;
var total = 1;
if (!isNaN(parseFloat($(this).find(".qnty").val()))) {
qnty = parseFloat($(this).find(".qnty").val());
}
if (!isNaN(parseFloat($(this).find(".price").val()))) {
price = parseFloat($(this).find(".price").val());
}
if (!isNaN(parseFloat($(this).find(".hours").val()))) {
hours = parseFloat($(this).find(".hours").val());
}
total = qnty * price * hours;
$(this).find(".total").val(total.toFixed(2));
});
// sum all totals
var sum = 0;
$(".total").each(function () {
if (!isNaN(this.value) && this.value.length != 0) {
sum += parseFloat(this.value);
}
});
// show values in netto, steuer, brutto fields
$("#netto").val(sum.toFixed(2));
$("#steuer").val(parseFloat(sum * 0.19).toFixed(2));
$("#brutto").val(parseFloat(sum + parseFloat(($("#steuer").val()))).toFixed(2));
}
// replace , with . and block writing letters
$.fn.ForceNumericOnly = function() {
return this.each(function() {
if($(this).data('forceNumericOnly')){ return; }
$(this).data('forceNumericOnly', true);
$(this).keydown(function(e) {
if(e.keyCode==188 || e.keyCode==110 || e.keyCode==108){
e.preventDefault();
$(this).val($(this).val() + '.');
}
var key = e.charCode || e.keyCode || 0;
return (key == 8 || key == 9 || key == 46 || key == 110 || key == 188 || key == 190 || (key >= 35 && key <= 40) || (key >= 48 && key <= 57) || (key >= 96 && key <= 105));
});
});
};
// execute function on element focus
$(document).on('focus', '.amount', function(){
$(this).ForceNumericOnly();
});

For the first question
1) you added "r" variable for rows limit in wrong place so add like below
var r = 1;
$('.addRow').click(function () {
if(r<10)
{
r++;
$('#t1').append('<tr id="row' + r + '" class="item"><td><select name="personal' + r + '" class="select"><optgroup label="Personal"><option selected="true" disabled="true" style="display:none">--auswählen</option><option value="koeche">Köche</option><option value="barkeeper">Barkeeper</option><option value="garderobiere">Garderobiere</option><option value="chauffeure">Chauffeure</option><option value="oberkellner">Oberkellner</option><option value="serviceleitung">Serviceleitung</option><option value="hilfskoch">Hilfskoch</option><option value="servicekraefte">Servicekräfte</option></optgroup></select></td><td><input name="anzahl' + r + '" class="qnty amount" value="" type="number" min="0" step="1"/></td><td><input name="preisps' + r + '" class="price amount" value="" /></td><td><input name="stunden' + r + '" class="hours amount" value="" /></td><td><input name="total' + r + '" class="total" value="" readonly="readonly" /></td><td><button type="button" name="remove" id="' + r + '" class="btn_remove">X</button></td></tr>');
}
});
// remove row when X is clicked
$(document).on("click", ".btn_remove", function () {
r--;
var button_id = $(this).attr("id");
$("#row" + button_id + '').remove();
});
after above change you will add only 10 row in the table.
2) Question you need to create one json from the created table structure and pass that json in the server side through ajax and in server side parsing your json and store that information in the database.
And from the table design look like it will be 2 table one table have master information and another detail table which have detail information.
Please let me know if you need sample code for that.

Related

Value of input text is empty after appending using jQuery

I am dynamically generating a form using AJAX and on the click of a button I add more input fields. But when I enter values in the input field and inspect in developer console,I don't see any value in the input text box.
Code for generating the form
$.ajax({
method: 'GET',
url: 'api/PayrollSystem/GetEmployeeSalaryAmount?AdminId=' + 1,
success: function(data) {
if (Object.keys(data).length == 0) {
$.alert({
title: 'Saved',
content: 'Account Number Saved!',
});
var row = ('<tr ><td colspan="3" text-align="center"> <b>No Registered Users</b></td></tr>');
$('.EmpTable').append(row);
} else {
$.each(data, function(index, value) {
var rows = ('<div id="form_div"><form method="post"><table class="table table-hover employee_table' + index + ' " align=center><thead><tr><td><b>Employee</td> <td><b>Amount</td></tr></thead><tbody><tr><td><b>' + value.FullName + '</b></td><td><input type="hidden" class="form-control Leavename" name="Leavename[]" value="Basic" placeholder="Enter Leave Name"> <input readonly class="form-control LeaveAmount" type="number" name="LeaveAmount[]" value=' + value.SalaryAmount + ' /><input class="form-control EmpId" type="hidden" name="Id[]" value=' + value.Id + ' /></td></tr><tr id="row' + index + 1 + '"><td><input type="text" class="form-control Leavename" name="Leavename[]" placeholder="Enter Leave Name"> </td><td> <input type="number" class="form-control LeaveAmount" name="LeaveAmount[]" placeholder="Enter Leave Amount"></td> </tr></tbody> </table> <input type="button" class="btn btn-success addRow" onclick="add_row(' + index + '); " value=" + Add More Payroll Item"></form> </div><hr />');
$('.EmpTable').append(rows);
});
}
}
});
Code for appending the row containing the new text box to the form
function add_row(index) {
$rowno = $(".employee_table tr").length;
$rowno = $rowno + 1;
$(".employee_table" + index + " tr:last").after("<tr id= 'row" + $rowno + "' > <td><input type='text' class='form-control Leavename' name='Leavename[]' placeholder='Enter Leave Name'> </td><td> <input type='number' name='LeaveAmount[]' class='form-control LeaveAmount' placeholder='Enter Leave Amount'></td><td> <input type='button' value='x' onclick=delete_row('row" + $rowno + "') ><br></td></tr>");
}
Immediate help will be well appreciated.
EDIT: My loop logic that gave no value when looping through the text boxes of each form generated.
$('#saveAdj').click(function() {
$('form').each(function() {
var thisForm = this;
alert($('.EmpId', thisForm).val());
alert($('.Leavename', thisForm).val());
alert($('.LeaveAmount', thisForm).val());
});
})

calculate sum of the each dynamic totals

I want to calculate sum of all totals in the below js fiddle, using the following code: http://jsfiddle.net/hEByw/7/
For reference i given the screenshot below. The total calculates the according to the qty*price dynamically. I want to add all totals and display as a grand total. Please anyone can help me regarding this. Thanks in advance
<script type='text/javascript'>
//<![CDATA[
$(window).load(function () {
var counter = 1;
$(document).ready(function () {
//To multiply two textbox values
$('#qty' + counter).keyup(calculate);
$(this).keyup(calculate);
function calculate(e) {
$('#total' + e.target.title).val($('#qty' + e.target.title).val() * $('#rates' + e.target.title).val());
}
$('#btnCalc').click(function () {
alert($('#qty').val());
});
$("#addButton").click(function () {
if (counter > 27) {
alert("Only 27 textboxes allow");
return false;
}
var newTextBoxDiv = $(document.createElement('div'))
.attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<label>Product #' + counter + ' : </label>' +
'<input type="text" size="60" name="product[]" placeholder="Product"\n\
id="product' + counter + '" value="" title = ' + counter + ' > \n\
<label>Quantity #' + counter + ' : </label>' +
'<input type="text" size="2" title = ' + counter + ' name="qty[]" \n\
id="qty' + counter + '" value="" > \n\
<label>Rate #' + counter + ' : </label>' +
'<input type="text" title = ' + counter + ' size="2" name="rates[]"\n\
id="rates' + counter + '" value="" > \n\
<label>Total #' + counter + ' : </label>' +
'<input type="text" title = ' + counter + ' size="3" name="total[]" id="total' + counter + '" value="" class="txt" onchange="calculate();"> ');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
$("#removeButton").click(function () {
if (counter == 0) {
alert("No more textbox to remove");
return false;
}
counter--;
$("#TextBoxDiv" + counter).remove();
});
});
});//]]>
</script>
<table>
<tr>
<td><strong>Select the products</strong>
<input type='button' value='Add Products' id='addButton'>
<input type='button' value='Remove Products' id='removeButton'>
</td>
</tr>
</table>
<table>
<tr>
<td>
<div id='TextBoxesGroup'></div>
</td>
</tr>
<tr>
<td>
<input type="hidden" id="countervalue" name="countervalue" style="display:none;">
</td>
</tr>
</table>
Grand Total : <p id="inputSum"></p>
Check this solution
http://jsfiddle.net/mgc2f5xj/
added a function to get total of all items
function getTotal(){
var totals = document.getElementsByName("total[]");
var total = 0;
for (var i=0; i< totals.length; i++){
total+= Number(totals[i].value);
}
document.getElementById("inputSum").innerText = total;
}

jQuery Calculations after appending more input fields

I am building an expense template an am having an issue regarding using jQuery Calculations and click functionality to append a set of input fields.
I am combining twooncodes, one to calculate the sum of the values in input fields, and the other to Add a new row of input fields when the user clicks so (these are also to be added to the sum). Problem is, the sum is not adding to the total from the newly appended rows. Only the default row of fields adds.
Any help is appreciated (Fiddle ex: http://jsfiddle.net/NicoleScotsburn/o8x02sjh/4/ )
Appending table with inputs code:
//Increment Variables
var items = $('#items');
var i = $('#items td').size() + 1;
var mileage = $('#mileage');
var j = $('#mileage td').size() + 1;
//Append Table Rows
$('#addItem').on('click', function() {
$('<tr><td> <label for="date"><input type="text" id="date" size="10" name="date_' + i +'" value="" placeholder="mm/dd/yyyy" /></label></td>' +
'<td> <label for="desc"><input type="text" id="desc" size="30" name="desc_' + i +'" /></label></td>' +
'<td> $<label for="entmt"><input type="text" id="sum" size="10" name="entmt_' + i +'" placeholder="0.00" /></label></td>' +
'<td> $<label for="meals"><input type="text" id="sum" size="10" name="meals_' + i +'" placeholder="0.00" /></label></td>' +
'<td> $<label for="other"><input type="text" id="sum" size="10" name="other_' + i +'" placeholder="0.00" /></label></td>' +
'<td> $<label for="travel"><input type="text" id="sum" size="10" name="travel_' + i +'" placeholder="0.00" /></label></td>' +
'<td> $<label for="lodging"><input type="text" id="sum" size="10" name="lodging_' + i +'" placeholder="0.00" /></label></td>' +
'<td> $<label for="hst"><input type="text" id="sum" size="10" name="hst_' + i +'" placeholder="0.00" /></label></td>' +
'<td> Remove</td></tr>').appendTo(items);
i++;
return false;
});
$('#addMileage').on('click', function() {
$('<tr><td> <label for="mdate"><input type="text" id="mdate" size="10" name="mdate' + j +'" value="" placeholder="mm/dd/yyyy" /></label></td>' +
'<td> <label for="mlocation"><input type="text" id="mlocation" size="30" name="mlocation' + j +'" value="" placeholder="" /></label></td>' +
'<td> <label for="km"><input type="text" id="km" size="10" name="km' + j +'" value="" placeholder="" />KM</label></td>' +
'<td> Remove</td></tr>').appendTo(mileage);
j++;
return false;
});
//Remove Buttons
$('body').on('click', '#remItem', function() {
if( i > 2 ) {
$(this).parents('tr').remove();
i--;
}
return false;
});
$('body').on('click', '#remMileage', function() {
if( j > 2 ) {
$(this).parents('tr').remove();
j--;
}
return false;
});
Calculation function: (This works assuming the id of the input is id="sum" and gets outputted to another input called totalsum.
$("input[id^=sum]").sum("keyup", "#totalSum");
I am not familiar with jQuery Calculations, but it looks like what you are doing can be achieved using plain jQuery or javascript. I did a quick google search for jquery sum and I found this other stackoverflow post that might help you. stackoverflow sum
You can add a class attribute called "sum" to all the fields you want to sum up and use the jquery marked as the answer. Once you get done calculating the total you can assign it to the total amount input field.
$('.sum').blur(function () {
var sum = 0;
$('.sum').each(function() {
sum += Number($(this).val());
});
$("#totalsum").val(sum);
});​​​​​​​​​

Removing a row from multiple rows javascript and jquery

My structure is like this
Itemid
itemname
itemdescription
itemprice
itemquantity
totalamount.
In this structure I have function to calculate the total (price*quantity). I have a add row function that lets add a row and a Grantotal function(adding all the totals). All I need to have is delete function, I have tried deleting the rows in many things but it is not working.
Here is my code:
$(document).ready(function () {
var counter = 2;
$("#addButton").click(function () {
if (counter > 100) {
alert("Only 100 textboxes allowed");
return false;
}
var newTextBoxDiv = $(document.createElement('tr'))
.attr("id", 'TextBoxDiv' + counter);
newTextBoxDiv.after().html('<td class="first"><input placeholder="Item Code ' + counter + '" class="itmcode" type="text" name="data[' + counter + '][0]" id="itemcode' + counter + '" ></td>' + '<td><input class="itmname" placeholder="Item Name ' + counter + '" type="text" name="data[' + counter + '][1]" id="itemname' + counter + '" ></td>' + '<td><input class="itmdesc" placeholder="Item DESC' + counter + '" type="text" name="data[' + counter + '][2]" id="itemdesc' + counter + '" ></td>' + '<td><input class="itmamnt" placeholder="Item AMT' + counter + '" type="text" name="data[' + counter + '][3]" id="itemamnt' + counter + '" /></td>' + '<td><input class="itmqty" placeholder="Item QTY ' + counter + '" type="text" name="data[' + counter + '][4]" id="itemqty' + counter + '" /></td>' + '<td><input type="text" name="total' + counter + '" id="total' + counter + '" class="total" /></td><td><button class="del">Delete</button></td>');
newTextBoxDiv.appendTo("#TextBoxesGroup");
counter++;
});
$(document).on('keyup', '.itmqty', function (ev) {
// grab ID to get row number
thisID = $(this).attr("id");
rowNum = thisID.slice(-1);
//get Amount entered
amt = $('#itemamnt' + rowNum).val();
//get QTY
qty = $('#itemqty' + rowNum).val();
$('#total' + rowNum).val(amt * qty);
currentCount = counter - 1;
var tot = 0;
$('.total').each(function () {
tot += parseFloat($(this).val());
});
$('#running_total').val(tot);
});
//$('#total').val($('#itm-qty').val() * $('#itm-amnt').val());
});
('#TextBoxesGroup').on('click','.del', function(){
if(counter==2){
alert("No More Rows to Remove");
return false;
}
counter--;
$("#TextBoxDiv" + counter).remove();
});
// $('#TextBoxesGroup').on('click','.del', function(){
// $(this).parents('tr:eq(0)').remove();
// });
I have tried this code also:
$('#TextBoxesGroup').on('click','.del', function(){
$(this).parents('tr:eq(0)').remove();
});
HTML
<input type="button" id="addButton" value=" Add Row " />
<table id="TextBoxesGroup">
<tr>
<td>
<input id="itemcode1" placeholder="Item Code 1" class="itmcode" />
</td>
<td>
<input id="itemname1" placeholder="Item Name 1" />
</td>
<td>
<input id="itemdesc1" placeholder="Item Description 1" />
</td>
<td>
<input id="itemamnt1" placeholder="Item Amount 1" class="itmamnt" />
</td>
<td>
<input id="itemqty1" placeholder="Item Qty 1" class="itmqty" />
</td>
<td>
<input id="total1" placeholder="Item Total 1" class="total" />
</td>
<td><button class="del">Delete</button></td>
</tr>
</table>
<table>
<tr>
<td>Running Total</td>
<td>
<input name="running_total" id="running_total" />
</td>
</tr>
</table>
Please let me know what mistake I made and help me in getting this.
The fiddle link simplied. few mistake like ('#TextBoxesGroup) here no $ symbol.And brace are not well balanced.
Instead count variable you code will be obsolete so use $('#TextBoxesGroup tr').length.
1)
$('#TextBoxesGroup').on('click','.del', function(){
$(this).closest("tr").remove();
});
2) Runningtotal value refresh code snippet.
var tot1 = 0;
$('#TextBoxesGroup tr td input.total').each(function () {
tot1 += parseFloat($(this).val());
});
$('#running_total').val(tot1);
Working Fiddle Demo

Autosum with generated fields JS

I'm a bit stuck with javascript again. Basically when you click a button a new row of fields will appear, giving them a new name just a different number.
I now need these fields to be able to auto sum by themself, i can do this with the first row I just don't know how to do them with the new generated ones.
The Javascript code:
<script language="javascript" type="text/javascript">
var i=2;
function addRow()
{
var tbl = document.getElementById('customersAdd');
var lastRow = tbl.rows.length;
var iteration = lastRow - 1;
var row = tbl.insertRow(lastRow);
var firstCell = row.insertCell(0);
var el = document.createElement('input');
el.placeholder = 'Quantity';
el.type = 'text';
el.name = 'quantity' + i;
el.id = 'quantity' + i;
firstCell.appendChild(el);
var secondCell = row.insertCell(1);
var el2 = document.createElement('input');
el2.placeholder = 'Description';
el2.type = 'text';
el2.name = 'description' + i;
el2.id = 'description' + i;
secondCell.appendChild(el2);
var thirdCell = row.insertCell(2);
var el3 = document.createElement('input');
el3.placeholder = 'Rate';
el3.type = 'text';
el3.name = 'rate' + i;
el3.id = 'rate' + i;
thirdCell.appendChild(el3);
var forthCell = row.insertCell(3);
var el4 = document.createElement('input');
el4.placeholder = 'Amount';
el4.type = 'text';
el4.name = 'amount' + i;
el4.id = 'amount' + i;
forthCell.appendChild(el4);
// alert(i);
i++;
// alert(i);
}
function startCalc(){
interval = setInterval("calc()",1);
}
function calc(){
one = document.main.quantity1.value;
two = document.main.rate1.value;
document.main.amount1.value = (one * 1) * (two * 1);
}
function stopCalc(){
clearInterval(interval);
}
</script>
The HTML code:
<form action="submit.php" name="main" method="post">
<table style="border-collapse: collapse;" border="0" align="center" width="50%" class="horiz" id="customersAdd">
<tr>
<td align="center"><br/>
<input class="text" style="width:100%" type="button" align="middle"value="Add Aditional Row" onClick="addRow()" /></td>
</tr>
<tr align="center">
<td>
<br />
<input placeholder="Quantity" type="text" name="quantity1" id="quantity1" onFocus="startCalc();" onBlur="stopCalc();" />
<br /></td>
<td>
<br />
<input placeholder="Description" type="text" name="description1" id="description1"/>
<br /></td>
<td>
<br />
<input placeholder="Rate" type="text" name="rate1" id="rate1" onFocus="startCalc();" onBlur="stopCalc();"/>
<br /></td>
<td>
<br />
<input placeholder="Amount" type="text" name="amount1" id="amount1" onBlur="stopCalc();" onFocus="startCalc();" readonly="true" />
<br /></td>
</tr>
</table></form>
To make things easier for anyone who could help me I have made this in JSBin to see it easier of what i want to do. Any suggestions are appreciated.
http://jsbin.com/atabaz/1/edit
Thanks
In the end I managed to find a way on how to do this myself, if anyone is interested take a look at this:
http://jsfiddle.net/2sYgE/
var currentItem = 1;
$('#customersAdd').on('keyup', '.quantity, .rate, .amount', calculateRow);
$('#addnew').click(function() {
currentItem++;
$('#customersAdd').append('<tr><td><input placeholder="Quantity" type="text" name="quantity' + currentItem +'" id="quantity' + currentItem +'" class="qty form-input-rate" /></td><td><input placeholder="Description" type="text" name="description' + currentItem +'" id="description' + currentItem +'" class="form-input-rate"/></td><td><input placeholder="Rate" type="text" name="rate' + currentItem +'" id="rate' + currentItem +'" class="rate form-input-rate"/></td><td><input placeholder="Amount" type="text" name="amount' + currentItem +'" id="amount' + currentItem +'" class="cal form-input-rate"/></td></tr>'
);
});
function calculateSum() {
var sum = 0;
$(".cal").each(function () {
if (!isNaN(this.value) && this.value.length != 0) {
sum += parseFloat(this.value);
}
});
}
function calculateRow() {
var cost = 0;
var $row = $(this).closest("tr");
var qty = parseFloat($row.find('.qty').val());
// changed the following line to only look within the current row
var rate = parseFloat($row.find('.rate').val());
cost = qty * rate;
if (isNaN(cost)) {
$row.find('.cal').val("0");
} else {
$row.find('.cal').val(cost);
}
calculateSum();
}
Polling for changes is a very inefficient and error–prone way to do form updates. Listening for change events is a better way to go as it uses fewer resources and waits until the user has finished updating the control before doing anything. There is also an input event that can be used, but it's not suitable here as it will update the form as the user enters values. Much better to wait for the user to finish entering values, then do the update.
I've re–factored your code below, it's not ready for production but it should give you some idea of how to go about it. Table rows are cloned as it's much faster than creating all the elements from scratch. Then names are modified, though this isn't really necessary. There is no need for ID attributes.
Cloning only works reliably here if inline listeners are used on the form controls. If the initial listeners are dynamically attached, you'll have to add them each time a row is added as listeners added using addEventListener are not cloned.
I haven't included any input validation, if the user puts in junk, they get junk back. You should validate input to check that appropriate values are being entered, and also format the displayed values for presentation.
<script type="text/javascript">
function addRow(element) {
var form = element.form;
var table = form.getElementsByTagName('table')[0];
var tbody = table.tBodies[0];
var num = tbody.rows.length - 1;
var row = table.rows[1].cloneNode(true);
var input, inputs = row.getElementsByTagName('input')
// Update input names
for (var i=0, iLen=inputs.length; i<iLen; i++) {
input = inputs[i];
input.name = input.name.replace(/\d+$/,num);
input.value = '';
}
tbody.insertBefore(row, tbody.rows[tbody.rows.length - 1]);
}
function updateRow(element) {
var form = element.form;
var num = element.name.replace(/^\D+/,'');
var value = form['quantity' + num].value * form['rate' + num].value;
form['amount' + num].value = (value == 0)? '' : value;
updateTotal(form);
}
function updateTotal(form) {
var elements = form.elements;
var name = /^amount/;
var total = 0;
var value;
for (var i=0, iLen=elements.length; i<iLen; i++) {
if (name.test(elements[i].name)) {
total += parseFloat(elements[i].value);
}
}
form.total.value = total;
}
</script>
<form action="submit.php" name="main" method="post">
<table style="border-collapse: collapse;" border="0" align="center"
width="50%" class="horiz" id="customersAdd">
<tr>
<td><br>
<input class="text" style="width:100%" type="button"
align="middle"value="Add Aditional Row" onclick="addRow(this)">
</td>
</tr>
<tr>
<td>
<input placeholder="Quantity" name="quantity1" onblur="updateRow(this);">
</td>
<td>
<input placeholder="Description" type="text" name="description1">
</td>
<td>
<input placeholder="Rate" name="rate1" onchange="updateRow(this);">
</td>
<td>
<input placeholder="Amount" name="amount1" readonly>
</td>
</tr>
<tr>
<td colspan="3" style="text-align: right">Total
<td><input name="total" readonly>
</tr>
</table>
<input type="reset">
</form>

Categories