On Press Tab append input field - javascript

I working in an attendance register where I have a table with a date on which the user should enter the work duration like 1 or 1.5 or 2 which means 1 as a full day, 1.5 as one and half day and so on.
The Problem which I am facing is I have javascript where I have given on click to append the input field. but what I am looking for is whenever the user press tab it should go to the next input field.
Please take a look at the screenshot of the layout.
Here is javascript code :
$(function () {
$("td").on("click", function() {
var $this = $(this);
var tdID = $(this).attr("id");
var $input = $("<input>", {
value: $this.text(),
type: "text",
style: "width:40px",
id:"myInput",
blur: function() {
$this.text(this.value);
saveEidatedData(tdID);
},
keyup: function(e) {
if ((e.which === 13)&&(e.which === 9)) $input.blur();
},
}).appendTo( $this.empty() ).focus();
});
});
Any help will be highly appreciated. Thanks in advance.

I think something like this? You may also use arrow keys, to remove the arrow key functionality just delete it from the 'arr' array
var sftDown = false;
$(document).on({
keydown: function(e) {
//37 - 40 = arrows keys
//13 = enter
//9 = tab ( should auto move with tab)
var arr = [9,13,37,38,39,40];
if ( e.which == 16 ) sftDown = true;
if ( $.inArray(e.which, arr) !== -1 ) {
var main = $(this).closest('#table');
var rows = main.find('tr');
var cells = main.find('input[type="text"]');
var downAmount = cells.length/rows.length;
var move = 1;
switch (e.which) {
case 9:
move = 0;
break;
case 40:
case 13:
move = downAmount;
break;
case 38:
move = downAmount * -1;
break;
case 37:
move *= -1;
break;
}
if ( sftDown ) move *= -1;
var i = cells.index(this) + move;
if ( i >= cells.length ) i %= cells.length;
if ( i < 0 ) i = cells.length + i;
cells[i].focus();
}
},
keyup: function(e) {
if ( e.which == 16 ) sftDown = false;
}
},'#table input[type="text"]');
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tbody id="table">
<tr>
<td><input type="text" /></td>
<td><input type="text" /></td>
<td><input type="text" /></td>
<td><input type="text" /></td>
</tr>
<tr>
<td><input type="text" /></td>
<td><input type="text" /></td>
<td><input type="text" /></td>
<td><input type="text" /></td>
</tr>
<tr>
<td><input type="text" /></td>
<td><input type="text" /></td>
<td><input type="text" /></td>
<td><input type="text" /></td>
</tr>
</tbody>
</table>

instead of doing it in JavaScript, you should populate the day with the text box having attribute of tabindex starting from some number and increment it to +1 for each row it should be start from where the last row tabindex ended.
if you doing it in JavaScript it would take extra time to make it work also you need to place extra checks.
like below example click on the first field and press tab it will move to the next input field.
To do as per my suggestion, it helps you to update time easily for specific day, as well as to populate the day's from array / object data type.
<tr>
<td><input type="text" tabindex="1" value="1" /></td>
<td><input type="text" tabindex="2" value="2" /></td>
<td><input type="text" tabindex="3" value="3" /></td>
</tr>
<tr>
<td><input type="text" tabindex="4" value="4" /></td>
<td><input type="text" tabindex="5" value="5" /></td>
<td><input type="text" tabindex="6" value="6" /></td>
</tr>

Related

Getting text values from dynamic HTML table

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>

when checkbox is checked not able to fetch data that are against that checkbox

I have data that is displayed in the form of a table and each row has a checkbox.
I am trying to fetch the data of each row when the checkbox is clicked against that row.
<tr>
<td><input type="text" name="child_name"></td>
<td><input type="text" name="child_age"></td>
<td><input type="checkbox" ></td>
</tr>
<tr>
<td><input type="text" name="child_name"></td>
<td><input type="text" name="child_age"></td>
<td><input type="checkbox" ></td>
</tr>
These will get generated dynamically, so the naming needs to same for the input box, however when i am fetching the value typed by the user,it fetches the value of only first row, and the values is getting repeated multiple times
$(document).ready(function(){
$('input[type="checkbox"]').click(function(){
if($(this).prop("checked") == true){
$tr = $(this).closest('tr');
var arr = [];
var data = $tr.children("td").map(function(){
var one = $("[name='child_name']").val();
var two = $("[name='child_age']").val();
arr.push(one)
arr.push(two)
return arr;
}).get();
console.log(data);
$('#post-result').append(data);
}
else if($(this).prop("checked") == false){
console.log("Checkbox is unchecked.");
}
});
});
Can anyone please tell how to resolve the issue
The name attribute in this case could complicate things a little bit. What I would do is use data-attributes to have specific identifiers for each row. Something like this:
UPDATED
I changed the behavior to work with dynamically added rows.
Using $(document).on("click"... you can affect future elements of the same type while $("[type='checkbox']").click() works only for currently existing elements.
I also took some liberty in expanding the example.
var children = [];
$(document).on("click", ".child-selector", function() {
var id = $(this).data("id");
if($(this).is(":checked")) {
var info = [];
info.push($(".child-name[data-id='"+ id +"']").val());
info.push($(".child-age[data-id='"+ id +"']").val());
console.log(info);
// An example of using objects to give some structure to the data
// and then store it to an array with all the checked rows
var child = {};
child.id = id;
child.name = $(".child-name[data-id='"+ id +"']").val();
child.age = $(".child-age[data-id='"+ id +"']").val();
children.push(child);
console.log(children);
} else {
console.log("Checkbox is unchecked.");
// An example of removing the specific children from the array
children.forEach(function(child, index) {
if(child.id == id) {
children.splice(index, 1);
}
});
console.log(children);
}
});
var clickCounter = 0;
var dataCounter = 13;
$("#add-child").click(function() {
var html = '<tr>'+
'<td><input type="text" class="child-name" data-id="'+ dataCounter +'" value="Child '+ clickCounter +'"></td>'+
'<td><input type="text" class="child-age" data-id="'+ dataCounter +'" value="'+ clickCounter +'"></td>'+
'<td><input class="child-selector" type="checkbox" data-id="'+ dataCounter +'"></td>'+
'</tr>';
$("table").append(html);
clickCounter++;
dataCounter++;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td><input type="text" class="child-name" data-id="9" value="John Connor"></td>
<td><input type="text" class="child-age" data-id="9" value="12"></td>
<td><input class="child-selector" type="checkbox" data-id="9"></td>
</tr>
<tr>
<td><input type="text" class="child-name" data-id="10" value="Jane Connor"></td>
<td><input type="text" class="child-age" data-id="10" value="12"></td>
<td><input class="child-selector" type="checkbox" data-id="10"></td>
</tr>
<tr>
<td><input type="text" class="child-name" data-id="11" value="Tom Connor"></td>
<td><input type="text" class="child-age" data-id="11" value="13"></td>
<td><input class="child-selector" type="checkbox" data-id="11"></td>
</tr>
<tr>
<td><input type="text" class="child-name" data-id="12" value="T800"></td>
<td><input type="text" class="child-age" data-id="12" value="1"></td>
<td><input class="child-selector" type="checkbox" data-id="12"></td>
</tr>
</table>
<button type="button" id="add-child">Add Child</button>
Now, if you need to send the data via post you should review your usage of name because as it currently is it would only send one value.
You can use the context parameter of $(selector [, context]) to only search inside the current <tr>:
$(document).ready(function() {
$('input[type="checkbox"]').click(function() {
if ($(this).prop("checked") == true) {
$tr = $(this).closest('tr');
var arr = [];
var one = $("[name='child_name']", $tr).val();
var two = $("[name='child_age']", $tr).val();
arr.push(one)
arr.push(two);
console.log(arr);
$('#post-result').append(arr);
} else if ($(this).prop("checked") == false) {
console.log("Checkbox is unchecked.");
}
});
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<table>
<tr>
<td><input type="text" name="child_name" value="A Name"></td>
<td><input type="text" name="child_age" value="A Age"></td>
<td><input type="checkbox"></td>
</tr>
<tr>
<td><input type="text" name="child_name" value="B Name"></td>
<td><input type="text" name="child_age" value="B Age"></td>
<td><input type="checkbox"></td>
</tr>
</table>
<pre id="post-result"></pre>

enter key to follow the tabindex (in scenario where enter key is changed to behave as tab)

I have a 3x3 table within a form. By default tab key moves the cursor in horizontal directions on these input fields. When a tabindex is given ( Like in the example below) the tab key moves cursor columns wise instead of row wise, as I needed.
With various sources from SO answers, I came up with the Jquery to use enter key as tab. But, could not figure out how to follow the tabindex as achieved above , i.e by pressing enter key instead of cursor moving row-wise, i want it to move in column wise. Below is what I have so far, any help is appreciated.
Demo of how it currently works. http://jsfiddle.net/unCu5/125/
Source of below code: jquery how to catch enter key and change event to tab
<table>
<tr>
<td><input tabindex="1" placeholder="1" /></td>
<td><input tabindex="2" placeholder="2" /></td>
<td><input tabindex="3" placeholder="3" /></td>
</tr><tr>
<td><input tabindex="1" placeholder="1" /></td>
<td><input tabindex="2" placeholder="2" /></td>
<td><input tabindex="3" placeholder="3" /></td>
</tr><tr>
<td><input tabindex="1" placeholder="1" /></td>
<td><input tabindex="2" placeholder="2" /></td>
<td><input tabindex="3" placeholder="3" /></td>
</tr>
</table>
$('input').live("keypress", function(e) {
/* ENTER PRESSED*/
if (e.keyCode == 13) {
/* FOCUS ELEMENT */
var inputs = $(this).parents("form").eq(0).find(":input");
var idx = inputs.index(this);
if (idx == inputs.length - 1) {
inputs[0].select()
} else {
inputs[idx + 1].focus(); // handles submit buttons
inputs[idx + 1].select();
}
return false;
}
})
#Dekel solution work for the html scenario he displayed, but I have a different type of HTML on view source. How do I fix this
Instead of just focus the next input element, you can find the next element (based on the tabindex) and focus on him:
$('input[tabindex^="2"]');
Check this example:
$(document).ready(function () { // Will only run once the page Document Object Model (DOM) is ready for JavaScript code
// Create a jQuery object containing the html element 'input'
// Create a .not() method to exclude buttons for keypress event
$(":input:not(:disabled)").not($(":button")).keypress(function(evt) {
// If the keypress event code is 13 (Enter)
if (evt.keyCode == 13) {
// get the attribute type and if the type is not submit
itype = $(this).prop('type');
if (itype !== 'submit') {
currentTabindex = $(this).attr('tabindex');
if (currentTabindex) {
nextInput = $('input[tabindex^="'+ (parseInt(currentTabindex)+1) +'"]');
if (nextInput.length) {
nextInput.focus();
return false;
}
}
}
}
});
});
<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<table>
<tr>
<td><input tabindex="1" placeholder="1" /></td>
<td><input tabindex="4" placeholder="4" /></td>
<td><input tabindex="7" placeholder="7" /></td>
</tr><tr>
<td><input tabindex="2" placeholder="2" /></td>
<td><input tabindex="5" placeholder="5" /></td>
<td><input tabindex="8" placeholder="8" /></td>
</tr><tr>
<td><input tabindex="3" placeholder="3" /></td>
<td><input tabindex="6" placeholder="6" /></td>
<td><input tabindex="9" placeholder="9" /></td>
</tr>
</table>
The code doesn't support go back from the last input to the first. You will need to write it explicitly.
Updated version - fix wrong tabindex values
The original question didn't mention that tabindex could repeat or don't have sequential values.
This code will "fix" the values of tabindex based on the order in the code AND the values of the tabindex. It will support both repeated tabindex values and non sequential values (1, 2, 3, 6, 7):
function fixTabIndex() {
// Find all inputs. Their order will be the same order they appear inside your html.
inputs = $('input');
// Save the original HTML order of the inputs (we need this to compare their order in the HTML in case or equal two tabindex
inputs_original = $('input');
// Sort the inputs by their tabindex values and their position in the DOM
// More info on Array.prototype.sort: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort
inputs.sort(function(a, b) {
if ($(a).attr('tabindex') == $(b).attr('tabindex')) {
// If tabindex is equal - sort by the position in the DOM
if (inputs_original.index(a) < inputs_original.index(b)) {
return -1;
} else {
return 1;
}
} else if ($(a).attr('tabindex') < $(b).attr('tabindex')) {
return -1;
} else {
return 1;
}
});
// Set the new value of the tabindex based on the position in the sorted array
inputs.each(function(i, el) {
$(el).attr('tabindex', i+1);
});
}
$(document).ready(function () {
// First we need to fix the tabindex values:
fixTabIndex();
$("input").keypress(function(evt) {
// If the keypress event code is 13 (Enter)
if (evt.keyCode == 13) {
// Make sure this is not a submit input
if ($(this).prop('type') !== 'submit') {
currentTabindex = $(this).attr('tabindex');
if (currentTabindex) {
nextInput = $('input[tabindex^="'+ (parseInt(currentTabindex)+1) +'"]');
if (nextInput.length) {
nextInput.focus();
return false;
}
}
}
}
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<table>
<tr>
<td><input tabindex="1" placeholder="1" /></td>
<td><input tabindex="2" placeholder="2" /></td>
<td><input tabindex="3" placeholder="3" /></td>
</tr><tr>
<td><input tabindex="1" placeholder="1" /></td>
<td><input tabindex="2" placeholder="2" /></td>
<td><input tabindex="3" placeholder="3" /></td>
</tr><tr>
<td><input tabindex="1" placeholder="1" /></td>
<td><input tabindex="2" placeholder="2" /></td>
<td><input tabindex="3" placeholder="3" /></td>
</tr>
</table>

Issue with the way data is displayed in confirm box

I have a form with multiple text boxes where I can type a material name and in another box I can type the material price.
When the user clicks submit I am displaying a confirm box with the entered material(s) and price(s). In this confirm box I want to show all entered matr_name with the associated matr_price (one per line). I just can not seem to make it display as I want, the below script outputs like this:
matr_name
matr_price
matr_name
matr_price
etc.
I want it to display like this:
matr_name: matr_price
matr_name: matr_price
matr_name: matr_price
etc.
All I got is the below script which gives me the correct output, just not displayed as I want it in the confirm box.
Script
var matr_name = $("input[name*='matr']").map(function() {
return $(this).val()}).get().join('\n');
var confirm_form = confirm("Rep:\n" + matr_name);
console.log("Mart.: " + matr_name);
if(confirm_form == true)
{
return true;
}
else {
return false;
}
}
Part of the form:
<tr>
<td><input type="text" name="matr_name[]" id="matr_name" ></td>
<td><input type="text" name="matr_price[]" id="matr_price"/></td>
</tr>
<tr>
<td><input type="text" name="matr_name[]" id="matr_name" ></td>
<td><input type="text" name="matr_price[]" id="matr_price"/></td>
</tr>
<tr>
<td><input type="text" name="matr_name[]" id="matr_name" ></td>
<td><input type="text" name="matr_price[]" id="matr_price"/></td>
</tr>
<tr>
<td><input type="text" name="matr_name[]" id="matr_name" ></td>
<td><input type="text" name="matr_price[]" id="matr_price"/></td>
</tr>
<input type="submit" name="submit_name" id="submit_id" class="submit" value="Done" onclick="javascript:return show_confirm();"/>
You can put different strings after the value depending on the name:
var matr_name = $("input[name*='matr']").map(function() {
return $(this).val() + ($(this).attr('name') == 'matr_name[]' ? ': ' : '\n');
}).get().join('');
or:
var matr_name = $("input[name*='matr']").map(function() {
if ($(this).attr('name') == 'matr_name[]') {
return $(this).val() + ': ';
} else {
return $(this).val() + '\n';
}
}).get().join('');

Jquery: sum input text fields

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/

Categories