I am trying to get the values from an html table.
I have tried row.cells[j].innerHTML which returns <input name="ctl00$ctl00$ctl00$MainContent$Nav$SiteContent$Text2" type="text" id="MainContent_Nav_SiteContent_Text2" maxlength="5">
I have also tried row.cells[j].innerHTML.text, row.cells[j].innerHTML.value, and row.cells[j].outterHTML which all return undefined. Any ideas?
An overview of what I want happening: user enter values in the dynamic table, adding / deleting rows as needed. Once table is filled, user clicks save which calls GetTableValues() which loops through the table adding each fields value to a string. Each value is separated by % and each row is separated by #. I then assign that string to a hidden field which I can access in my VB.Net code which then parses the data to save to a database.
It is looping through table but (as seen in the logs below), it does not get the values from the table
Here is the javascript and html of the table and looping through the table.
function GetTableValues() {
var s = "";
console.log("enter function");
//Reference the Table.
var table = document.getElementById("dataTable");
//Loop through Table Rows.
for (var i = 1; i < table.rows.length; i++) {
//Reference the Table Row.
var row = table.rows[i];
console.log("outside nest " + s);
for (var j = 1; j < 6; j++) {
console.log("i= " + i + " j= " + j);
//Copy values from Table Cell to JSON object.
console.log("inside nest " + row.cells[j].innerHTML +"%");
s = s + row.cells[j].innerHTML +"%";
}
console.log("outside again " + s);
s = s + "#";
}
document.getElementsByName("drawingsHidden").value = s
console.log(document.getElementsByName("drawingsHidden").value);
}
<table id="dataTable" style="width:100%">
<tr>
<th>Check Box</th>
<th>CAGE</th>
<th>Dwg #</th>
<th>Dwg Rev</th>
<th>Prop Rev</th>
<th>Issued Rev</th>
<th>Status</th>
</tr>
<tr>
<td><input type="checkbox" id="chkbox" /></td>
<td><input type="text" id="Text2" maxlength="5" runat="server" text=""/></td>
<td><input type="text" id="DRAWINGNUM" maxlength="20" runat="server" text=""/></td>
<td><input type="text" id="DRAWINGREV" maxlength="2" runat="server" text=""/></td>
<td><input type="text" id="PROPREV" maxlength="2" runat="server" text=""/></td>
<!--tie these fields to the drawing tracking form-->
<td><input type="text" id="ISSUEDREV" maxlength="2" runat="server" text=""/></td>
<td><input type="text" id="Text3" maxlength="20" runat="server" text=""></td>
</tr>
</table>
enter function
outside nest
i= 1 j= 1
inside nest <input name="ctl00$ctl00$ctl00$MainContent$Nav$SiteContent$Text2" type="text" id="MainContent_Nav_SiteContent_Text2" maxlength="5" text="">%
i= 1 j= 2
inside nest <input name="ctl00$ctl00$ctl00$MainContent$Nav$SiteContent$DRAWINGNUM" type="text" id="MainContent_Nav_SiteContent_DRAWINGNUM" maxlength="20" text="">%
i= 1 j= 3
inside nest <input name="ctl00$ctl00$ctl00$MainContent$Nav$SiteContent$DRAWINGREV" type="text" id="MainContent_Nav_SiteContent_DRAWINGREV" maxlength="2" text="">%
i= 1 j= 4
inside nest <input name="ctl00$ctl00$ctl00$MainContent$Nav$SiteContent$PROPREV" type="text" id="MainContent_Nav_SiteContent_PROPREV" maxlength="2" text="">%
i= 1 j= 5
inside nest <input name="ctl00$ctl00$ctl00$MainContent$Nav$SiteContent$ISSUEDREV" type="text" id="MainContent_Nav_SiteContent_ISSUEDREV" maxlength="2" text="">%
outside again <input name="ctl00$ctl00$ctl00$MainContent$Nav$SiteContent$Text2" type="text" id="MainContent_Nav_SiteContent_Text2" maxlength="5" text="">%<input name="ctl00$ctl00$ctl00$MainContent$Nav$SiteContent$DRAWINGNUM" type="text" id="MainContent_Nav_SiteContent_DRAWINGNUM" maxlength="20" text="">%<input name="ctl00$ctl00$ctl00$MainContent$Nav$SiteContent$DRAWINGREV" type="text" id="MainContent_Nav_SiteContent_DRAWINGREV" maxlength="2" text="">%<input name="ctl00$ctl00$ctl00$MainContent$Nav$SiteContent$PROPREV" type="text" id="MainContent_Nav_SiteContent_PROPREV" maxlength="2" text="">%<input name="ctl00$ctl00$ctl00$MainContent$Nav$SiteContent$ISSUEDREV" type="text" id="MainContent_Nav_SiteContent_ISSUEDREV" maxlength="2" text="">%
Picture of the table
row.cells[j] is a TD Element, not an Input element.
By doing console.log(row.cells[j]) it's the easiest way to detect what is actually hold by some property. Then, having that element all it takes is to query for a child element Input. const EL_input = row.cells[j].querySelector("input"). Now that you have your input Element: const value = EL_input.value
Don't overuse ID selectors. Specially not in a table. It makes no sense for columns to contain elements with IDs, you might either run into a duplicated IDs issue or actually you don't necessarily need a Table.
Use NodeList.prototype.forEach(). It's simpler and easier than using daunting for loops.
You could also create some nifty DOM helpers to ease on your self Querying the DOM for elements
Use .console.log() or debugger to test your code.
// DOM helpers:
const EL = (sel, par) => (par || document).querySelector(sel);
const ELS = (sel, par) => (par || document).querySelectorAll(sel);
// Task:
const getTableValues = () => {
let str = "";
ELS("#dataTable tbody tr").forEach(EL_tr => {
ELS("td", EL_tr).forEach(EL_td => {
str += EL("input", EL_td).value + "%";
});
str += "#";
});
EL("#drawingsHidden").value = str
};
EL("#test").addEventListener("click", getTableValues);
#dataTable {
width: 100%;
}
<table id=dataTable>
<thead>
<tr>
<th>Check Box</th>
<th>CAGE</th>
<th>Dwg #</th>
<th>Dwg Rev</th>
<th>Prop Rev</th>
<th>Issued Rev</th>
<th>Status</th>
</tr>
</thead>
<tbody>
<tr>
<td><input type=checkbox></td>
<td><input type=text maxlength=5></td>
<td><input type=text maxlength=20></td>
<td><input type=text maxlength=2></td>
<td><input type=text maxlength=2></td>
<td><input type=text maxlength=2></td>
<td><input type=text maxlength=20></td>
</tr>
</tbody>
</table>
<button id=test type=button>CLICK TO TEST</button><br>
<input id=drawingsHidden type=text>
var table = document.getElementsByTagName('table')[0]
var td = table.getElementsByTagName('td')[0]
var input = td.getElementsByTagName('input')[0]
console.log(input.value)
<table>
<tr>
<td><input value=7><td>
</tr>
</table>
Related
I am new in javascript and facing a problem. I have invoice rows which can be added by pressing on a button. Now i want to calculate the total amount for each row separately(for which the formula is (quantity * price). And the total of all rows combined should become the total of the invoice. The problem is that when I enter the price and quantity in first row, it calculates the total but when I add a new row, it does not calculate the total for new added row after entering the value. Kindly help me in this regard.
function myFunction() {
var x = document.getElementById("price").value;
var y = document.getElementById("quantity").value;
if (x != "") {
document.getElementById("total").value = x * y;
}
}
function add_fields() {
var tableid = document.getElementById('product_table');
var row = document.createElement("tr");
row.innerHTML =
'<td><input type="text" name="price" id="price" oninput="myFunction()"> </td>' +
'<td><input type="text" name="quantity" id="quantity" oninput = "myFunction()" > < /td>' +
'<td><input type="text" name="total" id="total" readonly></td>';
tableid.appendChild(row);
}
table,
tr,
td,
th {
border: 1px black solid;
}
<table>
<thead>
<th>Price</th>
<th>Quantity</th>
<th>Total</th>
</thead>
<tbody id="product_table">
<tr>
<td><input type="text" name="price" id="price" oninput="myFunction();"></td>
<td><input type="text" name="quantity" id="quantity" oninput="myFunction();"></td>
<td><input type="text" name="total" id="total" readonly></td>
</tr>
</tbody>
<input type="button" name="submit" value="Add Row" onclick="add_fields();">
Use event delegation instead - add a single listener to the container, listen for input events. Then, from the target property of the event, you can get the changed input element. Use .closest to get to the parent <tr>, and then from its descendants, you can get to the associated price, quantity, and total <input>s, and assign values appropriately.
Note that this adds the handler using Javascript, rather than with inline HTML attributes, which are generally considered to be pretty poor practice and can be difficult to manage. Also, duplicate IDs in a single document is invalid HTML - IDs aren't needed anyway here, because the inputs you want are always in a predictable order inside each <tr>. So, you can remove the id and the onclick attributes from the HTML and from the row.innerHTML string:
const table = document.getElementById('product_table');
table.addEventListener('input', ({ target }) => {
const tr = target.closest('tr');
const [price, quantity, total] = tr.querySelectorAll('input');
total.value = price.value * quantity.value;
});
function add_fields() {
var row = document.createElement("tr");
row.innerHTML =
'<td><input type="text" name="price"> </td > ' +
'<td><input type="text" name="quantity"> </td>' +
'<td><input type="text" name="total" readonly></td>';
table.appendChild(row);
}
table,
tr,
td,
th {
border: 1px black solid;
}
<table>
<thead>
<th>Price</th>
<th>Quantity</th>
<th>Total</th>
</thead>
<tbody id="product_table">
<tr>
<td><input type="text" name="price"></td>
<td><input type="text" name="quantity"></td>
<td><input type="text" name="total" readonly></td>
</tr>
</tbody>
<input type="button" name="submit" value="Add Row" onclick="add_fields();">
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>
i created a button that allows you to clone a tree of elements. This is my code:
function add_party(number) {
var n = number.replace("party", "");
var newparty = document.getElementById("party"+n);
var div = document.createElement("div");
var con = document.getElementById("party1").innerHTML;
document.createElement("div");
div.id = 'party' + ++n;
div.innerHTML = con;
newparty.parentNode.insertBefore(div, newparty.nextSibling);
renumberDivs(div, n, "div","party");
}
This is my HTML:
<div id="party1">
<h1>Party 1</h1>
<table>
<tbody>
<tr>
<th>party name:</th>
<td><input type="text" name="name1" value="some name"></td>
</tr>
<tr>
<th>party time:</th>
<td><input type="text" name="time1" value="some time"></td>
</tr>
</tbody>
</table>
<input type="button" onclick="add_party(this.parentNode.id)" value="add party">
</div>
However, since each element has an unique ID or name the clone should not have the same IDs or names. Instead the new IDs and names should add up by 1. So the cloned tree should look like this:
<div id="party2">
<h1>Party 2</h1>
<table>
<tbody>
<tr>
<th>party name:</th>
<td><input type="text" name="name2" value=""></td>
</tr>
<tr>
<th>party time:</th>
<td><input type="text" name="time2" value=""></td>
</tr>
</tbody>
</table>
<input type="button" onclick="add_party(this.parentNode.id)" value="add party">
</div>
Also, the input values should be empty for the clone. How can i do it with javascript? (no jQuery please).
Thank you.
EDIT:
this code updates the count numbers so they always appear in order:
function renumberDivs(el, n, tagn, ass) {
while (el = el.nextSibling) {
if (el.tagName && el.tagName.toLowerCase() == tagn){
el.id = ass + ++n;
}
}
}
Generally, this solution is a 2-step process:
manipulate existing parties one by one from the last to the insert point.
insert new party to the insert point.
function add_party(divId) {
var party = document.getElementById(divId);
var newParty = party.cloneNode(true);
var allParties = document.querySelectorAll('div[id^="party"]');
var newId = parseInt(divId.replace('party', ''), 10) + 1;
for(var i = allParties.length-1; i > newId-2; i--) {
allParties[i].setAttribute('id', 'party' + (i+2));
allParties[i].querySelector('h1').innerHTML = 'Party ' + (i+2);
var partyInputs = allParties[i].querySelectorAll('input[type="text"]');
for(var j = 0; j < partyInputs.length; j++) {
var prefix = partyInputs[j].getAttribute("name").replace(/\d+/, "");
partyInputs[j].setAttribute("name", prefix + (i+2));
}
}
newParty.setAttribute('id', 'party' + newId);
newParty.querySelector('h1').innerHTML = 'Party ' + newId;
var inputs = newParty.querySelectorAll('input[type="text"]');
for(var i = 0; i < inputs.length; i++) {
var prefix = inputs[i].getAttribute("name").replace(/\d+/, "");
inputs[i].setAttribute("name", prefix + newId);
inputs[i].setAttribute("value", "");
inputs[i].value = "";
}
party.parentNode.insertBefore(newParty, party.nextSibling);
}
<div id="party1">
<h1>Party 1</h1>
<table>
<tbody>
<tr>
<th>party name:</th>
<td><input type="text" name="name1" value="some name"></td>
</tr>
<tr>
<th>party time:</th>
<td><input type="text" name="time1" value="some time"></td>
</tr>
</tbody>
</table>
<input type="button" onclick="add_party(this.parentNode.id)" value="add party">
</div>
you'd better attach event to element using addEventListener. I found it works fun. Please refer to DEMO..., but there is a question, for the new generated form, there is no event handler attached, so you should attach new event handler for new generated form. if you can use jQuery or some others, you can use function like Delegate that bind event handler automatically
I have the table:
<table id="form_Dependentes" width="100%" cellpadding="0" cellspacing="0" class="form">
<tr>
<th colspan="4" valign="middle" scope="col">Dependentes</th>
</tr>
<tr>
<td colspan="2"><label>Nome</label><input type="text" name="depNome_01" maxlength="128" /></td>
<td width="20%"><label>Parentesco</label><input type="text" name="depParentesco_01" maxlength="16" /></td>
<td width="20%"><label>Data Nasc.</label><input type="text" name="depDataNasc_01" maxlength="10" /></td>
</tr>
<tr>
<td colspan="2"><label>Nome</label><input type="text" name="depNome_02" maxlength="128" /></td>
<td width="20%"><label>Parentesco</label><input type="text" name="depParentesco_02" maxlength="16" /></td>
<td width="20%"><label>Data Nasc.</label><input type="text" name="depDataNasc_02" maxlength="10" /></td>
</tr>
... etc.
</table>
This table is formatted to be printed and used online. Online, I wish to put buttons to add and remove those lines with input tags above the header. Is not complicate to format the html, but I was thinking about removing and adding tr lines using xml javascript capabilities, but don't know exactly how...
Edit: I don't get what so wrong with this question that is getting negative. Whatever... I'm working in this code:
var cadFormTableRow;
var cadFormTable;
function cadFormAtivar(){
document.getElementById("form_FotoUpload").innerHTML = 'Foto (máximo 1MB): <input name="foto" type="file" accept="image/*;capture=camera">';
document.getElementById("form_Assinatura").innerHTML = '';
document.getElementById("form_Dados").innerHTML = 'Dependentes: <button type="button" onclick="cadFormDep(1);"> + </button> <button type="button" onclick="cadFormDep(-1);"> - </button><br /><button type="button" onclick="cadFormTestar();">Enviar</button>';
cadFormTable = document.getElementById("form_Dependentes");
var nr = cadFormTable.rows.length;
cadFormTableRow = cadFormTable.rows[1];
console.log("Rows: "+nr);
//console.log("Row: "+cadFormTableRow.outerHTML);
for(i=0; i<nr-1; i++){
cadFormTable.deleteRow(1);
}
}
function cadFormDep(a){
if(a>0){
cadFormTable.appendChild(cadFormTableRow);
} else {
var nr = cadFormTable.rows.length;
cadFormTable.deleteRow(nr-1);
}
}
The problem seams to be appendChild is not good, I should go deep in HTMLTableElement, I guess, that's what I like to choose the better approach first... If I could make it work, I'll answer myself, I don't mind you don't like it, it's a free world, right?
It seams HTMLTableElement is the best approach for inserting and deleting rows. HTMLTableElement.insertRow creates a row linked with the original object. Here is the same code with HTMLTableElement corrections needed:
var cadFormTableRow;
var cadFormTable;
function cadFormAtivar(){
document.getElementById("form_FotoUpload").innerHTML = 'Foto (máximo 1MB): <input name="foto" type="file" accept="image/*;capture=camera">';
document.getElementById("form_Assinatura").innerHTML = '';
document.getElementById("form_Dados").innerHTML = 'Dependentes: <button type="button" onclick="cadFormDep(1);"> + </button> <button type="button" onclick="cadFormDep(-1);"> - </button><br /><button type="button" onclick="cadFormTestar();">Enviar</button>';
cadFormTable = document.getElementById("form_Dependentes");
var nr = cadFormTable.rows.length;
cadFormTableRow = cadFormTable.rows[1];
for(i=0; i<nr-1; i++){
cadFormTable.deleteRow(1);
}
}
function cadFormDep(a){
if(a>0){
var row = cadFormTable.insertRow(-1);
var html = cadFormTableRow.innerHTML.replace(/{n}/g, String(cadFormTable.rows.length-1));
row.innerHTML = html;
console.log("Row: "+html);
} else {
var nr = cadFormTable.rows.length;
cadFormTable.deleteRow(nr-1);
}
}
I think working with the cells and inputs as string were easier in this case - I'd pick a sample (as below) and add a number replacing {n} by a numbering:
<tr>
<td colspan="2"><label>Nome</label><input type="text" name="depNome_{n}" maxlength="128" /></td>
<td width="20%"><label>Parentesco</label><input type="text" name="depParentesco_{n}" maxlength="16" /></td>
<td width="20%"><label>Data Nasc.</label><input type="text" name="depDataNasc_{n}" maxlength="10" /></td>
</tr>
This way, every the information will have an unique name.
I have a table including input text fields with the basic structure below. I am having trouble building a function to iterate all rows in the table and sum all the values of input fields beginning with BFObel where the value of the field beginning with BFOkto are the same. So for the basic example below the sum for value 1111 would be 2000 and the sum for value 1112 would be 3000. Each sum would then be written to an inputfield with the id field1111, field1112 etc...
<table>
<tr id="BFOrow1">
<td><input type="text" id="BFOtxt1" value="text"/></td>
<td><input type="text" id="BFOkto1" value="1111" /></td>
<td><input type="text" id="BFObel1" value="1000" /></td>
</tr>
<tr id="BFOrow2">
<td><input type="text" id="BFOtxt2" value="text"/></td>
<td><input type="text" id="BFOkto2" value="1111" /></td>
<td><input type="text" id="BFObel2" value="1000" /></td>
</tr>
<tr id="BFOrow3">
<td><input type="text" id="BFOtxt3" value="text"/></td>
<td><input type="text" id="BFOkto3" value="1112" /></td>
<td><input type="text" id="BFObel3" value="1000" /></td>
</tr>
<tr id="BFOrow4">
<td><input type="text" id="BFOtxt4" value="text"/></td>
<td><input type="text" id="BFOkto4" value="1112" /></td>
<td><input type="text" id="BFObel4" value="1000" /></td>
</tr>
<tr id="BFOrow5">
<td><input type="text" id="BFOtxt5" value="text"/></td>
<td><input type="text" id="BFOkto5" value="1112" /></td>
<td><input type="text" id="BFObel5" value="1000" /></td>
</tr>
</table>
You'll want to use an object literal to track your results and an "attribute starts with" selector to find the text inputs:
var accumulator = { };
$('table input[id^=BFOkto]').each(function() {
var sum_id = this.id.replace(/^BFOkto/, 'BFObel');
if(!accumulator[this.value])
accumulator[this.value] = 0;
accumulator[this.value] += parseInt($('#' + sum_id).val(), 10);
});
// accumulator now has your results.
Don't forget the second argument to parseInt() so that you don't get tripped up by values with leading zeros (which look like octal without a specified radix).
For example: http://jsfiddle.net/ambiguous/QAqsQ/ (you'll need to run this in a browser with an open JavaScript console to see the resulting accumulator).
var sum1111 = 0;
$('input[value="1111"]').each(function() {
var ordinal = $(this).attr('id').replace('BFOkto', '');
sum1111 += parseInt($('#BFObel' + ordinal).val());
});
At the end, sum1111 should equal 2000.
For reuse, wrap the logic in a function:
function getSum(BFOkto) {
var sum = 0;
var ordinal = null;
$('input[value="' + BFOkto + '"]').each(function() {
ordinal = $(this).attr('id').replace('BFOkto', '');
sum += parseInt($('#BFObel' + ordinal).val());
});
return sum;
}
And then call:
getSum('1111');
getSum('1112');
A different approach: find all input fields with prefix BFOkto, for each, find the input with prefix BFObel sharing same parent and accumulate its value
ref = $("table td input[id^=BFOkto]");
var sums = new Object();
ref.each(function(){
val = parseInt($(this).closest('tr').find("td input[id^=BFObel]").val(), 10);
property = 'i'+ this.value;
sums[property] = (sums[property] || 0 ) + val;
});
alert(sums['i1111']);
alert(sums['i1112']);
sums will be an object with properties
i1111 = 2000
i1112 = 3000
Despite javascript allows it, it is better not to use pure numeric properties for objects (associative arrays), hence the i prefix
The running example is here:
http://jsfiddle.net/TbSau/1/