How to get the average of all the dynamic inputs - javascript

I can't find the average of all the inputs. My code only reads the input that i stated in html, but doesn't read the other dynamic ones.
Heres my code:
$(document).ready(function(){
// adds a new row
$(".addCF").click(function(){
$("#customFields").append('<tr valign="top"><th scope="row"><label for="customFieldName">Custom Field</label></th><td><input type="text" class="code" id="customFieldName" name="customFieldName[]" value="" placeholder="Input Name" /> Add Remove</td></tr>');
});
// deletes the row
$("#customFields").on('click','.remCF',function(){
$(this).parent().parent().remove();
});
$("#customFields").on('click','.add',function(){
$("#customFields").append('<tr valign="top"><th scope="row"><label for="customFieldName">Custom Field</label></th><td><input type="text" class="code" id="customFieldName" name="customFieldName[]" value="" placeholder="Input Name" /> Add Remove</td></tr>');
});
$("#click").click(function(){
var isbn = document.getElementById('customFieldName').value;
alert(isbn / $("input").length)
$("#averageGrade").text("Average Grade: " + isbn)
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="form-table" id="customFields">
<tr valign="top">
<th scope="row"><label for="customFieldName">Custom Field</label></th>
<td>
<input type="text" class="code" id="customFieldName" name="customFieldName[]" placeholder="Input Name" />
Add
</td>
</tr>
</table>
<button id = "click" class = "btn btn-primary" >Hi</button>
<p id = "averageGrade">Average Grade:</p>
Please help!
Thanks!

Each element.id must be unique - please change customFieldName to a class, and then iterate over the inputs and calculate the average. Also, you can reuse the same class for all "add" buttons and save that string in a variable so you don't have to paste it multiple times.
let inputTemplate = '<tr valign="top"><th scope="row"><label>Custom Field</label></th><td><input type="text" class="customFieldName code" name="customFieldName[]" value="" placeholder="Input Name" /> Add Remove</td></tr>';
$(document).ready(function() {
// adds a new row
$("#customFields").on('click', '.addCF', function() {
$("#customFields").append(inputTemplate);
});
// deletes the row
$("#customFields").on('click', '.remCF', function() {
$(this).parent().parent().remove();
});
$("#click").click(function() {
let fields = $('.customFieldName'),
total = 0;
for (let field of fields)
total += Number(field.value);
let average = total / fields.length;
$("#averageGrade").text("Average Grade: " + average);
})
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table class="form-table" id="customFields">
<tr valign="top">
<th scope="row"><label>Custom Field</label></th>
<td>
<input type="text" class="customFieldName code" name="customFieldName[]" placeholder="Input Name" />
Add
</td>
</tr>
</table>
<button id="click" class="btn btn-primary">Hi</button>
<p id="averageGrade">Average Grade:</p>

First of all, you need a way to select all the fields. Since id must (should) be unique, you could use the name or the class .code and remove id="customFieldName".
Then, getElementById, as its name suggests, returns one element. You need to select them all! If you're using class names, you can use getElementsByClassName, or querySelectorAll, or, since you're already using jQuery, just $(".code"), along with a loop to read each input's value (it you use jQuery, you can also use each()).
var sum=0,count=0,average;
$(".code").each(function() {
var value=parseInt($(this).val());
//You may want to validate the field
if(!isNaN(value)) sum+=value;
count++;
});
average=sum/count;
...

As many has pointed out (including myself in the comment section), you are going about using the wrong selector. id is a unique selector, meaning that the script will look at the first instance of the id and then stop immediately after.
What you need to do is use a selector that goes through every occurance of its instance. This is why class selectors exist. That will be the first fix in your code.
How I would go about calculating the average, personally, would be to make an array and push(); the values of the grades into the array. We will also need to do a parseInt() to make sure that our values are in fact handled as numbers. Otherwise, they'll be interpreted as strings.
You will then need to loop through the array, sum the values and divide by the length of the array.
HTML Example:
<div class="row">
<div class="col-12">
<table class="table form-table" id="customFields">
<tr valign="top">
<th scope="row"><label>Custom Field</label></th>
<td>
<input type="number" class="customFieldName" placeholder="Input Number" />
Add
</td>
</tr>
</table>
</div>
</div>
<div class="row">
<div class="col-md-4">
<button id="calcAvrgBtn" class="btn-primary">Calculate average grade</button>
</div>
<div class="col-md-4">
<p id="averageCalc"></p>
</div>
</div>
jQuery Example:
$('.addCF').on("click", function() {
$("#customFields").append('<tr valign="top"><th scope="row"><label>Custom Field</label></th><td><input type="number" class="customFieldName" placeholder="Input Number" /> Remove</td></tr>');
});
$(document).on("click", "a.remCF" , function() {
$(this).parent().parent().remove();
});
$('#calcAvrgBtn').on("click", function() {
let gradeArr = [];
$('.customFieldName').each(function() {
gradeArr.push(parseInt($(this).val()));
});
let total = 0;
for(var i = 0; i < gradeArr.length; i++) {
total += gradeArr[i];
}
let avg = total / gradeArr.length;
$('#averageCalc').text("The average grade is: "+avg);
});
Codepen example can be found here.
Snippet Example:
$('.addCF').on("click", function() {
$("#customFields").append('<tr valign="top"><th scope="row"><label>Custom Field</label></th><td><input type="number" class="customFieldName" placeholder="Input Number" /> Remove</td></tr>');
});
$(document).on("click", "a.remCF" , function() {
$(this).parent().parent().remove();
});
$('#calcAvrgBtn').on("click", function() {
let gradeArr = [];
$('.customFieldName').each(function() {
gradeArr.push(parseInt($(this).val()));
});
let total = 0;
for(var i = 0; i < gradeArr.length; i++) {
total += gradeArr[i];
}
let avg = total / gradeArr.length;
$('#averageCalc').text("The average grade is: "+avg);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/4.5.0/css/bootstrap.min.css" rel="stylesheet"/>
<div class="row">
<div class="col-12">
<table class="table form-table" id="customFields">
<tr valign="top">
<th scope="row"><label>Custom Field</label></th>
<td>
<input type="number" class="customFieldName" placeholder="Input Number" />
Add
</td>
</tr>
</table>
</div>
</div>
<div class="row">
<div class="col-md-4">
<button id="calcAvrgBtn" class="btn-primary">Calculate average grade</button>
</div>
<div class="col-md-4">
<p id="averageCalc"></p>
</div>
</div>

Related

I want to disable the selected Item from a Drop Down list for the next row's DropDown Dynamically

The HTML for the form is :
<form id="flowform" class="form" role="form" autocomplete="off">
<table id="add-flow-level" class="table table-striped table-borderless" style="width: 100%">
<thead>
<tr>
<th></th>
<th></th>
<th></th>
<th></th>
</tr>
</thead>
<tbody>
<tr>
<td>
<div class="col-sm-4">
<label class="required ">Min Amount</label>
<input type="text"
id="minAmount" name="minAmount" class="form-control min"
style="border-radius: 1rem; width: 183px;"
maxlength="100" required="required"
/>
<!-- onfocus = "maxAmountCheck(this.id);" -->
</div>
</td>
<td>
<div class="col-sm-4">
<label class="required ">Max Amount</label>
<input
type="text" id="maxAmount" name="maxAmount"
class="form-control max"
style="border-radius: 1rem; width: 183px;"
maxlength="100" required="required" />
<!-- onfocus = "maxAmountCheck(this.id);"/ -->
</div>
</td>
<td>
<div class="col-sm-4">
<label class="required">Approver</label>
<select class="form-control" id="approver" name="approver"
style="border-radius: 1rem; width: 183px;"
required="required" >
<!-- onfocus = "approverCheck(this.id);" -->
<option th:value="0">Select User</option>
<option th:each="usersList : ${usersList}"
th:value="${usersList.id}"
th:utext="${usersList.firstName +' '+ usersList.lastName}" />
</select>
</div>
</td>
<td>
<a href="#" id="addFlowLevelRow" class="btn btn-primary btn-label-left addFlowLevelRow" title="Add Next" style="margin-top: 18px;">
<i class="fa fa-plus" aria-hidden="true"></i>
</a>
</td>
</tr>
</tbody>
</table>
<br>
<div class="row">
<label class="control-label col-sm-5" style="margin-top: 8px;"></label>
<div class="col-sm-2">
<input type="submit" class="btn btn-primary btn-label-left"
value="Save" id="submitbtnflow" name="submitbtnflow"
style="border-radius: 1rem;">
</div>
<p id="msg" style="color: green;"></p>
</div>
</form>
js file
var countOfRows =1;
$(".addFlowLevelRow").click(function() {
var remv = "<a href='#' id='removeFlowLevelRow' class='btn btn-primary btn-label-left removeFlowLevelRow' title='Remove Row' style='margin-top: 33px;'><i class='fa fa-minus' aria-hidden='true'></i></a>";
var txt = $(this).closest("tr").find('#removeFlowLevelRow').attr('href');
if (txt == undefined && countOfRows < 5) {
var newRow = $(this).closest("tr").clone(true).appendTo("#add-flow-level").append(remv);
if(countOfRows == 4)
{
document.getElementsByClassName("addFlowLevelRow")[4].style.display = "none";
console.log("Removal of - button at row = "+countOfRows);
}
countOfRows++;
console.log("Number of row = "+countOfRows);
}
else if(countOfRows < 5){
var newRow = $(this).closest("tr").clone(true).appendTo("#add-flow-level");
if(countOfRows == 4)
{
document.getElementsByClassName("addFlowLevelRow")[4].style.display = "none";
console.log("Removal of - button at row = "+countOfRows);
}
countOfRows++;
console.log("Number of row =" +countOfRows);
}
var input = document.getElementsByClassName('max');
newRow.find('.min').val(input.value);
newRow.find('.max').val("");
newRow.find('#approver').val(0);
});
$(document).on('click', '#removeFlowLevelRow', function(e) {
console.log("view----");
$(this).closest("tr").remove();
countOfRows--;
console.log("After - Button count is = "+countOfRows);
});
$('#approver').on('change', function() {
alert("alerrt called");
var select = document.getElementById('approver');
var value = select.options[select.selectedIndex].value;
alert(value);
var index = value;
if (index > -1) {
// ${usersList}.splice(index, 1);
}
alert("ye ky tha"+select.value);
//return ${usersList};
});
I want that Super Admin to be disabled for the 2nd row and show values other than super Admin in that drop down.
Whenever the user clicks on + button it creates a clone of the row.
I have not created the new row separately but I want the new drop down to not have the value that are selected in the first drop down and this should go till 5 rows.
id's in the DOM should always be unique otherwise it can lead to strange behaviour in the page
so firstly you need to give each row's "approver" select element a separate id e.g. approver0,1,2... (or just remove the id) and instead have a common class for these elements e.g. "form-control approver"
Then in your onchange function, loop through the approver class and disable the select options that don't appear, here is some psuedo code to start working with
var a = document.getElementsByClassName("approver")
//loop through all approver select elements
for(i in a) {
if(a[i] = this) {
//do nothing if we loop to the element that has just been changed
}
else {
//if the approver select isn't the one we've just changed, loop through the options
options = a[i].childNodes
for(j in options){
if(options[j].value = this.value) {
//if the option matches the one we've just selected disable it
options[j].setAttribute("disabled")="disabled"
}
else {
//Otherwise re-enable it so we don't disable all elements by changing the selection
options[j].removeAttribute("disabled")
}
}
In this rudimentary example changing the next approver option will overwrite disabling the previous selection so you may need to also keep track of what has been selected in all other drop downs. but hopefully this gets you started

cost splitter javascript app

I am trying to make a cost splitter app for my roommates. I am explaining the app with an example. Suppose we are 4 members, there is a cost of 300, and 3 members (m1, m3, m4) participated in the expenditure (all have an equal share). Among them 2 members have paid the amount as follows: m3 paid 180 and m4 paid 120. Now the balance sheet will look like this:
m1(-100), m2(0), m3(+80), m4(+20)
I am not able to get all the form values properly and make the balance sheet.
<div>
<table id="dashboard">
<tr>
<th>TOTAL</th>
<th>member1</th>
<th>member2</th>
<th>member3</th>
<th>member4</th>
</tr>
<tr>
<td id="total"></td>
<td id="bmem1">0</td>
<td id="bmem2">0</td>
<td id="bmem3">0</td>
<td id="bmem4">0</td>
</tr>
</table>
</div>
<div id="newCostButton">
<button id="showForm" href="#">Add New Cost</button>
</div>
<form id="elForm">
<label>Cost:</label>
<input type="text" id="cost" placeholder="Add new cost">
<br>
<label><b>Participants:</b></label><br>
<span>member1</span>
<input type="checkbox" name="Participant" value="member1">
<span>member2</span>
<input type="checkbox" name="Participant" value="member2">
<span>member3</span>
<input type="checkbox" name="Participant" value="member3">
<span>member4</span>
<input type="checkbox" name="Participant" value="member4">
<br>
<b>contributors:</b><br>
member1
<input class= "contributors" type="text" name="member1">
member2
<input class= "contributors" type="text" name="member2">
member3
<input class= "contributors" type="text" name="member3">
member4
<input class= "contributors" type="text" name="member4">
<input type="submit" id="cal" value="calculate">
</form>
<div id="doc"></div>
<script>
$(function(){
var $newCostButton = $('#newCostButton');
var $elForm = $('#elForm');
var $cost = $('#cost');
$newCostButton.show();
$elForm.hide();
$newCostButton.on('click', function(){
$newCostButton.hide();
$elForm.show();
});
$('input:text').focus(function(){
$(this).val("");
});
function cal(){
var c = $cost.val();
var part = $('input:checked');
pCount = part.length;
var d= parseInt(c/pCount);
var contributors = $('.contributor');
var mem = [];
contributors.each(function(){
mem.push(parseInt($(this).val()));
});
console.log(mem);
for(var i=0;i<pCount;i++){
var r = mem[i]-d;
console.log(r);
}
}
$elForm.on('submit', function(e){
e.preventDefault();
cal();
});
</script>
I don't see where you import jquery
<script
src="https://code.jquery.com/jquery-3.3.1.min.js"
integrity="sha256-FgpCb/KJQlLNfOu91ta32o/NMZxltwRo8QtmkMRdAu8="
crossorigin="anonymous"></script>
why don't you use excel or google sheets?
I think this does something similar to what you are asking for. I simplified a few things like .hide() and .show(), but they're easy enough to add back. Hopefully something in here helps. If not, it was still a fun hour code challenge.
html:
<div>
<table class="dashboard">
<tr>
<th>TOTAL</th>
<th>member1</th><th>member2</th><th>member3</th<th>member4</th>
</tr>
<tr>
<td>0</td><td>0</td><td>0</td><td>0</td><td>0</td>
</tr>
</table>
</div>
<div class="newCost">
<span>Cost:</span><input type="text" placeholder="Add New Cost">
<button>Add New Cost</button>
</div>
<div class="participants">
<p>Participants:</p>
<span>member1</span><input type="checkbox">
<span>member2</span><input type="checkbox">
<span>member3</span><input type="checkbox">
<span>member4</span><input type="checkbox">
</div>
<div class="contributors">
<p>Contributors:</p>
member1 <input type="text">
member2 <input type="text">
member3 <input type="text">
member4 <input type="text">
</div>
<button class="calculate">calculate</button>
javascript:
String.prototype.toInt = function() { return parseInt(this, 10); };
$('.newCost button').on('click', function() {
let newCost = $('.newCost input').val().toInt();
$('.dashboard td')
.each(function(index, td) {
td.textContent = td.textContent.toInt() + (index ? newCost / 4 : newCost);
});
});
$('button.calculate').on('click', function() {
$('.participants input').each(function(index){
if (this.checked) {
this.checked = false;
let currentOwed = $(`.dashboard td:eq(${index + 1})`).text().toInt();
let contributed = $(`.contributors input:eq(${index})`).val().toInt();
let total = $('.dashboard td:eq(0)').text().toInt();
$('.dashboard td:eq(0)').text(total -= contributed);
$(`.dashboard td:eq(${index + 1})`).text(currentOwed -= contributed);
}
});
});
$('button').click(()=> { $('input[type=text]').val(''); });
https://jsfiddle.net/wn7bbxjk/

How to automatically breaks the page using jspdf

I have a option for the user to add more row based on user's choice. If I add a row more than 9 or 10 the page breaks and the last row became half. I have 3 buttons Add, Remove and Save.
Add - to add more row.
Remove - to reduce row.
Save - to save as pdf.
This is my script where I adding and removing row happens.
Script: Add and Remove row.
$(document).ready(function ()
{
$("#addMore").click(function ()
{
$("#customFields").append('<tr><td><input type="text" class="form-control"></td><td><input type="text" class="form-control"></td><td><input type="text" class="form-control"></td><td><input type="text" class="form-control"></td></tr>');
});
$("#removeRow").click(function()
{
if ($('#customFields tbody tr').length== 1)
{
alert('Error');
}
else
{
$('#customFields tr:last').remove();
}
});
});
Script: Save as pdf.
$("#save").click(function ()
{
var values = "";
//i is the iterator and c is the control. So every elements iterates through the second input of callback function in this case the c variable. c is literally this current element in the array/
$.each($(".form-control"), function(i, c)
{
values = values + $(c).val().trim(); // .trim() to remove white-space
});
if(values.length > 0)
{
html2canvas(document.getElementById("captureMyDiv"),
{
onrendered: function(canvas)
{
var img = canvas.toDataURL("image/png");
var doc = new jsPDF();
doc.addImage(img, 'JPEG',0,0);
doc.save('text.pdf');
}
});
}
else
{
alert('Cannot be left blank');
}
});
HTML:
<div class = "col-md-8" id = "captureMyDiv">
<div class="jumbotron text-center">
<h2 style = "text-align: center">REQUISITION AND ISSUE SLIP</h2>
<h4 style = "text-align: center">NATIONAL LABOR RELATIONS COMMISSION</h4>
</div>
<form class = "form-vertical">
<div class = "form-group">
<label class = "control-label">Department:</label>
<input type = "text" class = "form-control">
</div>
<div class = "form-group">
<label class = "control-label">Office:</label>
<input type = "text" class = "form-control">
</div>
<div class = "form-group">
<label class = "control-label">Responsibility Center Code:</label>
<input type = "text" class = "form-control">
</div>
<div class = "form-group">
<label class = "control-label">RIS No:</label>
<input type = "text" class = "form-control">
</div>
<div class = "form-group">
<label class = "control-label">SAI No:</label>
<input type = "text" class = "form-control">
</div>
</form>
<table class = "table" id = "customFields">
<thead>
<tr>
<th>Stock No.</th>
<th>Unit</th>
<th>Description</th>
<th>Quantity</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type="text" class="form-control"></td>
<td><input type="text" class="form-control"></td>
<td><input type="text" class="form-control"></td>
<td><input type="text" class="form-control"></td>
</tr>
</tbody>
</table>
<button type = "submit" class = "btn btn-primary" id = "addMore">+ Add</button>
<button type = "submit" class = "btn btn-danger" id = "removeRow">- Remove</button>
<button type = "submit" class = "btn btn-success" id = "save">Save</button>
</div>
Screenshot:
Use a combination of css propertyes to brake the elements on the page like
page-break-after,page-break-before,page-break-inside
for more info

passing array as argument in javascript

$(document).ready(function(){
var srno=1;
var srnoarray= new Array();
$(".addRow").click(function(){
var ToAppend='<tr><td><input type="text" class="form-control" style="width:40px;" name="srno_[]" id="id_srno_'+srno+'" value="'+srno+'" readonly="readonly" /></td>';
ToAppend+='<td>';
ToAppend+='<select class="form-control" name="product_name_'+srno+'" id="product_name_'+srno+'" onchange="return onSelectChangeajax(this.value,'+srno+')">';
ToAppend+='<option value="0">Select Product</option>';
ToAppend+='</select>';
ToAppend+='</td>';
ToAppend+='<td><input type="text" class="form-control" name="product_prise_'+srno+'" id="product_prise_'+srno+'" placeholder="Purchase Prise" onblur="calAmount('+srno+')" /></td><td><input type="text" class="form-control" name="product_qty_'+srno+'" id="product_qty_'+srno+'" value="1" placeholder="Quantity" onblur="calAmount('+srno+')"/></td><td><input type="text" class="form-control" name="product_amt_'+srno+'" id="product_amt_'+srno+'" placeholder="Amount" onblur="calAmount('+srno+')"/></td><td><img src="dist/img/removerow.png" onclick="deleteRow(this),deleteArrayVal.apply(this,'+srnoarray+');" /></td></tr>';
srnoarray.push(srno);
$("#purchaseItems").append(ToAppend);
console.log(srnoarray);
srno++;
});
});
function deleteRow(rwo)
{
var i=rwo.parentNode.parentNode.rowIndex;
document.getElementById("purchaseItems").deleteRow(i);
}
function deleteArrayVal(val)
{
console.log(val);
}
Above functions add the dynamic row and remove the row in table. I have created an array called srnoarray and I have added srno in that array on every tr get added dynamically. deleteRow is the function to remove tr, but when i remove tr i want to remove particular srno from srnoarray.
<img src="dist/img/removerow.png" onclick="deleteRow(this),deleteArrayVal('+srnoarray+');" />
I tried passing array as argument in the function but that is not of use.
how should I do that??
I see that you are trying to use the method here :
document.getElementById("purchaseItems").deleteRow(i);
For this, you might need to add the deleteRow as a prototype to work.
But please elaborate a little bit what exactly you want to delete from the array.
Thanks.
First of all, I would recommend to use a templating engine (e.g. handlebars)
to keep your js cleaner (no HTML in jquery). Improves readability.
I also would look at angularjs because then you will have it easier to keep your js data in synch with your DOM.
For your row remove button you could add a data attribute to each row so you can easily get the clicked row in your click handler.
Please have a look at the demo below and here at jsFiddle.
var row = $("#row-template").html(),
rowTemplate = Handlebars.compile(row),
purchasedItems = [];
/*
var context = {srno: 0};
var html = rowTemplate(context);
*/
function addRow() {
purchasedItems.push({
srno: purchasedItems.length+1,
products: [ {// just some dummy products
name:'pizza',
selected: 'selected'
},
{name:'pasta'
},
{name:'hamburger'}
]
});
console.log(purchasedItems);
refreshTable();
}
function refreshTable() {
$('#purchaseItems').empty();
$.each(purchasedItems, function(index, item) {
$('#purchaseItems').append(rowTemplate(item));
});
}
function getRowId(context) {
return $(context).parent().parent().attr('data-rowId');
}
/* not working --> needed to update the data in the array
$('#purchaseItems').on('change', '.productSelection', function() {
var index = getRowId(this);
console.log(index);
});
*/
$('#purchaseItems').on('click', '.removeRow', function() {
var index = getRowId(this);
console.log(index);
purchasedItems.pop(index);
console.log(purchasedItems);
refreshTable();
});
$('#add').click(function() {
addRow();
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/handlebars.js/3.0.3/handlebars.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script id="row-template" type="text/x-handlebars-template">
<tr data-rowId="{{srno}}">
<td>
<input type="text" class="form-control" style="width:40px;" name="srno_[]" id="id_srno_{{srno}}" value="{{srno}}" readonly="readonly" /></td>
<td>
<select class="form-control" name="product_name_{{srno}}" id="product_name_{{srno}}" class="productSelection">
{{#each products}}
<option value="{{this.name}}" {{this.selected}}>{{this.name}}</option>
{{/each}}
</select>
</td>
<td>
<input type="text" class="form-control" name="product_prise_{{srno}}" id="product_prise_{{srno}}" placeholder="Purchase Prise" onblur="calAmount({{srno}})" />
</td>
<td>
<input type="text" class="form-control" name="product_qty_{{srno}}" id="product_qty_{{srno}}" value="1" placeholder="Quantity" onblur="calAmount({{srno}})"/>
</td>
<td>
<input type="text" class="form-control" name="product_amt_{{srno}}" id="product_amt_{{srno}}" placeholder="Amount" onblur="calAmount({{srno}})"/>
</td>
<td>
<!--<img src="dist/img/removerow.png"--> <button class="removeRow">remove</button>
</td>
</tr>
</script>
<button id="add">add</button>
<div id="purchaseItems"></div>
function deleteArrayVal(value) {
var index = arr.indexOf(value);
if (index > -1) {
arr.splice(index, 1);
}
}

Cloning with javascript - renaming ID of form elements within a table

I have some code I am using that works well cloning the contents of a div as many times as needed.
The original code would rename the name/id of each form field. so the first clone the name would be "name1" second clone "name2" etc...
The problem is when I put the form fields within a div or a table for design purposes.
The code doesn't rename the form fields anymore as it seems to refer to the top elment which is the table or div (depending which I used)
Here is a cut down version of the code that contains everything needed for this example (can be copied into an editor and will work as is. You will see the field id's are not being renamed):
www.jsbin.com/oyavez/1/edit
<script type="text/javascript">
var formCounter = 0;
function init() {
document.getElementById('moreFields').onclick = moreFields;
moreFields();
}
function moreFields() {
formCounter++;
var newFields = document.getElementById('readroot').cloneNode(true);
newFields.id = '';
newFields.style.display = 'block';
var newField = newFields.childNodes;
for (var i=0;i<newField.length;i++) {
var theName = newField[i].name
if (theName)
newField[i].name = theName + formCounter;
}
var insertHere = document.getElementById('writeroot');
insertHere.parentNode.insertBefore(newFields,insertHere);
}
window.onload = moreFields;
</script>
<title>Add Orders IO TOC</title>
</head>
<body>
<!-- Template -->
<div id="readroot" style="display: none">
<table>
<tr><td colspan="2"><h3>Order <script>document.write(formCounter);</script></h2></td></tr>
<tr><td>Order ID: </td><td><input type="text" id="OrderID name="OrderID[]" ></input></td>
<td>Order Name: </td><td><input type="text" id="OrderName" name="OrderName[]" ></input></td>
</table>
<br /><br /><input type="button" value="Remove Above Order" style="width:200px;" onclick="this.parentNode.parentNode.removeChild(this.parentNode);" /><br /><br />
<!-- ROW -->
</div>
<!-- END Template -->
<!-- Start of form -->
<form method="get" action="form.php">
<table>
<tr><td align="center" colspan="2"><h2>Contract</h2></td></tr>
<!-- Static part of the form not to be cloned -->
<tr><td>Contract: </td><td><input type="text" id="Contract" name="Contract" ></input></td>
<td>Signed Date: </td><td><input type="text" id="datepicker0" name="SignedDate" ></input></td>
<tr><td align="center" colspan="2"><h2>Orders</h2></td></tr>
</table>
<!-- ROW -->
<!-- Cloned parts of the form appear here -->
<span id="writeroot"></span>
<table>
<tr><td align="center" > <input type="button" style="width:200px;" value="Add another order below" onclick="moreFields()" /></td>
<td align="center" ><input type="submit" value="Submit IO and all Orders" style="width:200px;" ></td></tr>
</table>
</form>
Anyone know how to get to the child of the table it would seem?
Thanks!

Categories

Resources