I met trouble with a script I have done,
this script should allocate an amount to different fields.
In fact here is the script, I will give you after the jsfiddle.
<script type="text/javascript">
function getItems()
{
var items = new Array();
var itemCount = document.getElementsByClassName("items");
for(var i = 0; i < itemCount.length; i++)
{
items[i] = document.getElementById("p"+(i+1)).value;
}
return items;
}
function setItems(items,payAmt)
{
//document.getElementById("troppercu").value = payAmt;
for(var i = 0; i < items.length; i++)
{
document.getElementById("p" + (i+1)).value = items[i];
}
}
function itemSum(items)
{
var sum = 0;
for(var i=0; i < items.length; i++)
{
sum = items[i] + sum;
}
return sum;
}
function payment(inputElm)
{
var items = getItems();
var payAmt = document.getElementById("montantacompte").value;
var i = 0;
var sum = itemSum(items);
while(payAmt != 0 && sum != 0)
{
var temp = items[i] - payAmt;
if(temp > 0)
{
items[i] = Math.round((temp)*100)/100;
break;
}
else if(temp < 0)
{
items[i] = 0;
payAmt = temp*-1;
}
i++;
sum = itemSum(items);
}
setItems(items, payAmt);
}
</script>
So I have an input in which I can write an amount, this amount will be allocated on the different fields.
Actually, the trouble is that when I put an amount that is the same as the principal amount, it freezes the screen. If I write the same amount + 1 cent, it does not freeze.
All information on the fields come from my database. that is written with PHP and MySQL.
The trouble comes when you write the same amount as in the principal so for that case it will freeze the screen if you write on the yellow box input 3654.58 I really do not understand why, in fact, it should not, because if I write 3654.59 all works, If I write more, it works also.
The problem is in while cycle,
you have
and
But what if
That causes your while cycle to work forever… I included temp = 0 case and then code worked fine:
http://jsfiddle.net/ywAU3/2/