I am having a hard time with this homework.
Trying to keep adding the multiplication of the new 2 fields the user will add.
Example:
first field 5 second field 5 = total is 5*5 = 25
But when the user clicks the add field, he would have:
first field = 5 second field 5
first field = 6 second field 6 total would be 5*5 + 6*6 = 61 and so forth
<script>
function calc(form) {
var box1 = parseFloat (form.leftover.value,10)
var box2 = parseFloat (form.charge.value,10)
var temp = new Array();
var Mbalance = ( box1 * box2 ) ;
temp.push(Mbalance) ;
for ( var i=0; i< temp.length ; i++ ) {
Mbalance = Mbalance+Mbalance ;
}
form.mbalance.value= Mbalance ;
}
// This script is identical to the above JavaScript function.
var ct = 1;
function new_link(form) {
ct++ ;
var div1 = document.createElement('div');
div1.id = ct;
// Link to delete extended form elements
div1.innerHTML = document.getElementById('newlinktpl').innerHTML ;
document.getElementById('newlink').appendChild(div1);
}
</script>
</script>
<form>
<div id="newlink">
<div>
<td width="423">What was the balance left over from last month ?</td>
<td width="19">$</td>
<td width="141"><input name="leftover" value="" maxlength="10" /></td>
</tr>
<tr>
<td>How much did you charge this month ?</td>
<td>$</td>
<td><input name="charge" value="" maxlength="10" /></td>
<br/>
</div></div>
<button type="submit" id="buttoncalculate" onclick="calc(this.form); return false; "></button>
<br />
<td width="462">Monthly Balance</td>
<td width="128"><input name="mbalance" value="" maxlength="10" /></td>
Add new
</form>
<form>
<!-- Template -->
<div id="newlinktpl" style="display:none">
<div>
<td width="423">What was the balance left over from last month ?</td>
<td width="19">$</td>
<td width="141"><input name="leftover" value="" maxlength="10" /></td>
</tr>
<tr>
<td>How much did you charge this month ?</td>
<td>$</td>
<td><input name="charge" value="" maxlength="10" /></td>
</div>
</div>
<form>
Here's one way you can do it. It's not necessarily the best, but it achieves what you want and I don't feel like completely rewriting what you had:
http://jsfiddle.net/HS6dt/2/
I added a class to the parent div of your two inputs as well as your two inputs. That way I can find the parent div, then find the descendant inputs, get their values and multiple them (note: I have no idea why you are multiplying those two values, it really doesn't make much sense, but whatever):
function calc(form) {
var total = 0;
var items = document.getElementsByClassName("item");
for (var i = 0; i < items.length; i++) {
var left = items[i].getElementsByClassName("leftover");
var charge = items[i].getElementsByClassName("charge");
total += parseFloat(left[0].value, 10) * parseFloat(charge[0].value, 10);
}
form.mbalance.value = total;
}
Related
Since I have couple of entries that needs to be divided with the number i provide (num1 variable), I find the difficulties to complete the task.
I want the loop to divide me and store value from each variable called listX with 34. There are 9 lists (each has different number) and i want each list to be divided with the number i provide, but to be divided first with 2, then with 3, then with 4, 5 ... up to the number i provide.
I figured out that it could be done best with objects, but I can't find the solution, since I'm not so experienced with this stuff. The ideal would be to get the objects like:
List1: 1st division: xxx
List1: 2nd division: xxx
List1: 34th division: xxx
...
List 8: 22nd division: xxx
...
List 9: 33rd divison: xxx
List 9: 34th division: xxx
"xth division" should be linked with the number i provided in the num1 variable
What I'm trying to get is something like this:
It asks me how many times i want my values to be divided, i type in 5. Then it asks me what are the values of my 9 inputs.
I declare to the first input 100. The result what I want should be:
100/1 = 1
100/2 = 50
100/3 = 33,33
100/4 = 25
100/5 = 20
Then I declare to the second input number 200. The result should be:
200/1 = 200
200/2 = 100
200/3 = 66,66
200/4 = 50
200/5 = 40
It goes all the way up until my last input...
What I'm trying to develop is D'Hondt method for seat allocations in the parliament that is being used for some countries.
Here is what I've got so far, but ofc, it is not working.
var array1 = [];
var list = "list";
function someFunction() {
var num1 = 34;
for (var i = 1; i <= num1; ++i) {
for (var j = 1; j <= 9; j++) {
array1[j] += document.getElementById(list + j).value / i;
array1[j] += "<br/>";
}
}
document.getElementById("demo1").innerHTML = list + j;
}
<tr>
<td><input type="text" id="list1" style="width:50px" onkeyup="someFunction()"></input></td>
<td><input type="text" id="list2" style="width:50px" onkeyup="someFunction()"></input></td>
<td><input type="text" id="list3" style="width:50px" onkeyup="someFunction()"></input></td>
<td><input type="text" id="list4" style="width:50px" onkeyup="someFunction()"></input></td>
<td><input type="text" id="list5" style="width:50px" onkeyup="someFunction()"></input></td>
<td><input type="text" id="list6" style="width:50px" onkeyup="someFunction()"></input></td>
<td><input type="text" id="list7" style="width:50px" onkeyup="someFunction()"></input></td>
<td><input type="text" id="list8" style="width:50px" onkeyup="someFunction()"></input></td>
<td><input type="text" id="list9" style="width:50px" onkeyup="someFunction()"></input></td>
</tr>
I think this is what you are looking for, but a couple of notes.
A couple of notes:
The input element does not have a closing tag.
type="text is the default for input elements, so you don't need
to write it.
Don't Repeat Yourself (DRY). Since all of your input elements need
the same styling, just set up a single CSS rule to style them all the
same way.
Don't use inline HTML event handlers. Separate your JavaScript from
your HTML and follow modern standards.
See the comments below for details.
// Get the number to divide by (You can get this anyway you want. A prompt is show here.):
var num = +prompt("How many calculations per input would you like?");
// Get all the table inputs into an array
var inputs = Array.prototype.slice.call(document.querySelectorAll("td > input[id^='input']"));
// Loop over the input array...
inputs.forEach(function(input){
// Set up an event handler for the input
input.addEventListener("input", someFunction);
});
function someFunction(){
var resultString = "";
for(var i = 0; i < num; i++){
// Do the math and build up the string
resultString += (this.value / (i + 1)) + "<br>";
}
// Update the output cell that corresponds to the input element with the results
document.querySelector("#" + this.id.replace("input", "output")).innerHTML = resultString;
}
td > input { width:50%; }
<table id="inout">
<tr>
<td><input id="input1"></td>
<td><input id="input2"></td>
<td><input id="input3"></td>
<td><input id="input4"></td>
<td><input id="input5"></td>
<td><input id="input6"><td>
<td><input id="input7"></td>
<td><input id="input8"></td>
<td><input id="input9"></td>
</tr>
<tr>
<td id="output1"></td>
<td id="output2"></td>
<td id="output3"></td>
<td id="output4"></td>
<td id="output5"></td>
<td id="output6"><td>
<td id="output7"></td>
<td id="output8"></td>
<td id="output9"></td>
</tr>
</table>
<div id="output"></div>
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 was able to create the template, but I'm not sure what to do from here.
When I click my add item button, I want the values to go into the text area I created on the bottom and change the subtotal and total as I keep adding items.
<html>
<head>
<meta charset = "utf-8">
<h1>Invoice Manager</h1>
<style type "text/css">
div {position: absolute;
top: 200px;
left: 90px;
z-index: 1;}
</style>
<script type = "text/javascript">
</script>
</head>
<body>
<table>
<tr>
<td align="right">Item Code:</td>
<td align="left"><input type="text" name="code" /></td>
</tr>
<tr>
<td align="right">Item Name:</td>
<td align="left"><input type="text" name="itemName" /></td>
</tr>
<tr>
<td align="right">Item Cost:</td>
<td align="left"><input type="text" name="cost" /></td>
</tr>
<tr>
<td align="right">Quantity:</td>
<td align="left"><input type="text" name="quantity" /></td>
</tr>
</table>
<div id="AddItemButton">
<td align = "left"><input type="submit" name="Submit" value="Add Item"></td>
</div>
</form>
<br></br> <br></br>
<font size = "5">Current Invoice</font>
<hr style = "height:2px;border:none;color:#333;background-color:#333;"></hr>
<p><label> <br>
<textarea name = "textarea"
rows = "12" cols = "180"></textarea>
</label></p>
<form>
<table>
<tr>
<td align="right">Subtotal:</td>
<td align="left"><input type="text" name="subtotal" /></td>
</tr>
<tr>
<td align="right">Sales Tax:</td>
<td align="left"><input type="text" name="tax" /></td>
</tr>
<tr>
<td align="right">Total:</td>
<td align="left"><input type="text" name="total" /></td>
</tr>
</table>
</form>
<form>
<input type = "button" value = "Add Item" onclick="textarea"/> <input type = "text" id = "cost" size ="20" />
</form>
That's what I have as a template. When I type in Item Code, Item Name, Item Cost and Quantity in those fields, I'd like those values to go in the text area on the bottom. I imagine I would need to write something in the script.
I'm not sure how to achieve this, but I was thinking that the first batch of info the user adds could equal a variable like a
Then the second values inputted could equal b
So let's say the user adds 3 items.
total = (a + b + c)
Or something like that.
Here's an example of what one "Add Item" would do. I'd like these submissions to appear in the text field I created like so
---Item Code--- ---Item Name--- ---Item Cost--- ---Quantity---
3 Dell 499 1
Any ideas on what I could do? I'm at a loss
Thanks
EDIT: I'm adding my script, I'm wondering if there's something wrong with it
<script type = "text/javascript">
function computeCost(){
var code = document.getElementById("code").value;
var a = code; // item code
var itemName = document.getElementById("itemName").value;
var b = itemName; // item name
var cost = document.getElementById("cost").value;
var c = cost; // calculate cost
var quantity = document.getElementById("quantity").value;
var d = quantity; // calculate quantity of items
var subtotal = document.getElementById("subtotal").value;
var e = c * d; // multiplying cost by quantity = subtotal
var tax = document.getElementById("tax").value;
var f = e * .7; // multiplying subtotal by tax(.7) = amount of tax owed
var total = document.getElementById("total").value;
var g = f + e; //adding tax to subtotal = total value
document.getElementByID("yo").value = total;
}
function clear()
{
document.getElementById("a","b","c","d", "e", "f", "g").reset();
} // end of clear
</script>
I dont have much time to give a polished script, but this provides basic functionality
EDIT: added script tags and basic JQUERY things
note that because of loading JQUERY from the internet, it wont work without internet connection, if you wish to use it without internet con, download the script and link it locally
<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script type = "text/javascript">
$(function(){
var textContent = $('textarea').val();
var textRow = "";
$('input[type=submit]').click(function(){
$('input[type=text]').each(function(){
textRow = textRow+$(this).val()+'\t';
});
textContent = textContent + '\n' + textRow;
textRow = "";
$('textarea').val(textContent);
});
});
</script>
this is just the necessary JS and HTML, nothing fancy:
function id(id){return document.getElementById(id);}
var val1 = 0;
var val2 = 0;
function val(){
val1 = parseInt(id("t1").value);
val2 = parseInt(id("t2").value);
id("total").innerHTML = ((val1 > 0 && val2 > 0))? val1 * val2 : 0;
}
<input id="t1" onkeyup="val()" type="number">
<input id="t2" onkeyup="val()" type="number">
<h1 id="total"></h1>
Please forgive my ignorance, as I'm pretty new to Java script. Here is what I'm trying to do. I have a form where users can enter in data to get reimbursed. It sums totals up horizontally, and then takes the final values and adds them vertically for a grand total.
I have everything working horizontally, and I can add the last 5 rows vertically, but when I add in the first two rows, it doesn't work. I get NaN for the answer. Here is the code.
<script type="text/javascript">
function calcWages(){
document.getElementById('wages').innerHTML = '';
var num2 = new Number(document.getElementById('hours').value);
var num3 = new Number(document.getElementById('rate').value);
document.getElementById('wages').innerHTML = ((num3 * num2).toFixed(2));
}
function calcMilage(){
document.getElementById('milage').innerHTML = '';
var num4 = new Number(document.getElementById('miles').value);
document.getElementById('milage').innerHTML = ((num4 * .555).toFixed(2));
}
function calcTotal(){
document.getElementById('total').innerHTML = '';
var num5 = new Number(document.getElementById('wages').value);
var num6 = new Number(document.getElementById('milage').value);
var num7 = new Number(document.getElementById('travel').value);
var num8 = new Number(document.getElementById('lodging').value);
var num9 = new Number(document.getElementById('food').value);
var num10 = new Number(document.getElementById('office').value);
var num11 = new Number(document.getElementById('other').value);
document.getElementById('total').innerHTML = (( num5 + num6 + num7 + num8 + num9 + num10 + num11).toFixed(2));
}
window.onload=function(){
document.getElementById('totalCalc').onclick = calcTotal;
}
</script>
<table>
<tr>
<td></td>
<td></td>
<td></td>
<td>
Total:
</td>
<td></td>
<td>
</td>
</tr>
<tr>
<td>Wages:</td>
<td>Hours:(8 a day Max)<input type="text" name="hours" id="hours" size="3" maxlength="3" onchange="calcWages()"></td>
<td>Rate:<input type="text" name="rate" id="rate" size="3" maxlength="5" onchange="calcWages()"></td>
<td>=</td>
<td><div id="wages"></div></td>
</tr>
<tr>
<td>Milage:</td>
<td>Miles<input type="text" name="miles" id="miles" size="3" maxlength="4" onchange="calcMilage()"></td>
<td>IRS rate ($0.555)</td>
<td>=</td>
<td><div id="milage"></div></td>
</tr>
<tr>
<td>
Travel: </td>
<td colspan="2">
<input type="text" name="tavelitem" id="travelitem" size="36"> </td>
<td>
=
</td>
<td><input type="text" name="travel" id="travel" size="3"> </td>
</tr>
<tr>
<td>Lodging:</td>
<td colspan="2"><input type="text" name="lodgingitem" id="lodgingitem" size="36"> </td>
<td>=</td>
<td><input type="text" name="lodging" id="lodging" size="3"></td>
</tr>
<tr>
<td>Food:</td>
<td colspan="2"><input type="text" name="fooditem" id="fooditem" size="36"> </td>
<td>=</td>
<td><input type="text" name="food" id="food" size="3"></td>
</tr>
<tr>
<td>Office Supplies:</td>
<td colspan="2"><input type="text" name="officesupplies" id="officesupplies" size="36"> </td>
<td>=</td>
<td><input type="text" name="office" id="office" size="3"></td>
</tr>
<tr>
<td>Other:</td>
<td colspan="2"><input type="text" name="otheritem" id="otheritem" size="36"></td>
<td>=</td>
<td><input type="text" name="other" id="other" size="3"></td>
</tr>
<tr>
<td></td>
<td><button id="totalCalc">Total</button></td>
<td>Grand Total:</td>
<td>=</td>
<td><div id="total"></div></td>
</tr>
</table>
The calcWages function and the calcMilage functions work, but I seem to be getting hung up and getting the results of those two, to work in the calcTotal function. I apologize if this doesn't make sense. Let me know, and I'll try to clarify. Thanks.
Here you're setting the .innerHTML
document.getElementById('milage').innerHTML = ((num4 * .555).toFixed(2));
// ^^^
But then you're getting the .value from the same element.
var num6 = new Number(document.getElementById('milage').value);
// ^^^
Seems like you should be using one or the other. If the .innerHTML works for the first, then you should fetch it as well, or vice versa (unless perhaps this is a textarea element).
Either that, or you intended to use the miles element instead of milage.
var num6 = new Number(document.getElementById('miles').value);
// ^^^
They functions don't return anything, so you cannot really get their results. However, you can just call them inside calcTotal:
function calcTotal(){
calcWages();
calcMilage();
// ...
}
From my comment: When you see yourself using variables names with a running index, using an array and/or a loop is likely to be a better solution.
Without changing your HTML, a cleaner solution would be:
var fields = ['wages', 'milage', ...];
function calcTotal(){
var sum = 0;
for (var i = 0; i < fields.length; i++) {
sum += +document.getElementById(fields[i]).value
}
document.getElementById('total').innerHTML = sum.toFixed(2);
}
You can also give the elements a common class to avoid listing their IDs in an array.
<script type="text/javascript">
function calcWages(){
document.getElementById('wagestotal').innerHTML = '';
var hours = new Number(document.getElementById('hours').value);
var rate = new Number(document.getElementById('rate').value);
document.getElementById('wagestotal').innerHTML = ((hours * rate).toFixed(2));
}
function calcMilage(){
document.getElementById('milagetotal').innerHTML = '';
var miles = new Number(document.getElementById('miles').value);
document.getElementById('milagetotal').innerHTML = ((miles * .555).toFixed(2));
}
function calcTotal(){
document.getElementById('total').innerHTML = '';
var wages = new Number(document.getElementById('wagestotal').innerHTML);
var milage = new Number(document.getElementById('milagetotal').innerHTML);
var travel = new Number(document.getElementById('travel').value);
var lodging = new Number(document.getElementById('lodging').value);
var food = new Number(document.getElementById('food').value);
var office = new Number(document.getElementById('office').value);
var other = new Number(document.getElementById('other').value);
document.getElementById('total').innerHTML = ((wages + milage + travel + lodging + food + office + other).toFixed(2));
}
window.onload=function(){
document.getElementById('totalCalc').onclick = calcTotal;
}
</script>
So this is the final script. I changes the names of the variables to things that make sense. The final hand up I was having was being able to ad the totals form the wages function, and the milage function into the the grand total. The part I had messed up was that I had:
var wages = new Number(document.getElementById('wagestotal').value);
var milage = new Number(document.getElementById('milagetotal').value);
Instead of:
var wages = new Number(document.getElementById('wagestotal').innerHTML);
var milage = new Number(document.getElementById('milagetotal').innerHTML);
in the calcTotal funciton. The user can enter stuff in to the form that this ties to, and it all gets totaled like it should. Thanks again for helping focus my thoughts.
I need to display the percentage each input value contains out of the full dataset.
So if the user inputs 3, 2 and 1. The "percent" inputfield should show "50, 30 and 20"
The thing is, i dont know how many inputs the form will get. It could be from 1 to any number.
The source html code is created by a partial view i created. The output is:
<table>
<tr>
<th>Name</th><th>Distributiob key</th><th>Percent</th>
</tr>
<tr>
<td>
House 1
</td>
<td>
<input type="text" size="5" value="0" id="LightPhysicalEntities_0__DistributionKey" name="LightPhysicalEntities[0].DistributionKey" />
</td>
<td>
<input type="text" size="5" id="LightPhysicalEntities_0__Percent" readonly=readonly />
</td>
</tr>
<tr>
<td>
House 2
</td>
<td>
<input type="text" size="5" value="0" id="LightPhysicalEntities_1__DistributionKey" name="LightPhysicalEntities[1].DistributionKey" />
</td>
<td>
<input type="text" size="5" id="LightPhysicalEntities_1__Percent" readonly=readonly />
</td>
</tr>
<tr>
<td>
House 3
</td>
<td>
<input type="text" size="5" value="0" id="LightPhysicalEntities_2__DistributionKey" name="LightPhysicalEntities[2].DistributionKey" />
</td>
<td>
<input type="text" size="5" id="LightPhysicalEntities_2__Percent" readonly=readonly />
</td>
</tr>
First field in the table is the title or name. Second is where the user punches in distribution number. Third is the readonly field with the calculated percentage.
The calculation should be done in javascript, but i cant quite crack the nut on how to get started, getting the inputs and setting the outputs.
A function like this should help (this will round down the percentages- replace the Math.floor if you want to handle differently):
function calcPcts() {
var distributions = $("[id$=DistributionKey]");
// Get the base first
var base = 0;
distributions.each(function () {
base += window.parseInt($(this).val(), 10);
});
// Now calculate the percentages of the individual ones
distributions.each(function () {
var input = $(this),
val = window.parseInt($(this).val(), 10),
pct = (val === 0) ? val : Math.floor((val / base) * 100);
$("#" + input.attr("id").replace("DistributionKey", "Percent")).val(pct);
});
}
If you add a class to the input fields you can use jQuery to get the number of items with that class. Then you can get the values and perform your calculations.
Here is an example:
var inputCount = $(".inputfield").length;
$("input[type='text']").change(function() {
var total = GetTotal();
for (i = 0; i < inputCount; i++) {
var inputValue = $('#LightPhysicalEntities_' + i + '__DistributionKey').val();
if (total != 0) {
var percent = inputValue / total;
$('#LightPhysicalEntities_' + i + '__Percent').val(percent);
}
}
});
function GetTotal() {
var total = 0;
for (i = 0; i < inputCount; i++) {
var inputValue = $('#LightPhysicalEntities_' + i + '__DistributionKey').val();
total += parseInt(inputValue);
}
return total;
}
Here is an example of the script working: http://jsfiddle.net/ZWuQr/