0

Hi, I am having some problem to integrate my PHP & JS codes.

The PHP code -

<?php 
for($i=1;$i<=3;$i++)
{
?>
<input type="text" id='rate<?php echo $i; ?>' /> * <input type="text" id='quantity<?php echo $i; ?>' onChange="updateValues(THIS);" /> = <span id='amount<?php echo $i; ?>' style="border: 2px solid black;padding:2px;"></span><br /><br />

<?php
}
?>
Total: <span id="total" style="border: 2px solid black;padding:2px;"></span>

The JS Code -

function updateValues(val) {

rate = document.getElementById(val).value;

quantity = document.getElementById(val).value;


document.getElementById(val).innerHTML = rate * quantity;


document.getElementById("total").innerHTML = total.val += val;
}

If I am defining the ID tags manually, then the thing works. But What if I need to do the same for 15 fields???

2
Contributors
2
Replies
3
Views
6 Years
Discussion Span
Last Post by anirban1087
0

There are many things in the code you provided, and have nothing to do with PHP but with JavaScript and DOM. First of all you have to validate that it is an integer what inserted. Then you should update and if a field has no value than it should considered as zero. When you add to a total variable this must has JavaScript global scope in order to abstract it. You can see it in code bellow, just ask specific if anything isn’t clear enough.

<html>
<head>
<script type="text/javascript">
var total = 0;
var rate = new Array();
var quantity = new Array(); 

String.prototype.isInteger = 
function()
{
	return this.match(/^\d+$/);
};
	  
function updateValues(val) 
{
	temp = val.split("_");
	id = temp[1]; 
	if(typeof(rate[id]) == "undefined") 
	{
		rate[id] = 0; 
	}
	if(typeof(quantity[id]) == "undefined") 
	{
		quantity[id] = 0; 
	}
	
	total = total - (rate[id] * quantity[id]);
	rate[id] = document.getElementById("rate_"+id).value;
	quantity[id] = document.getElementById("quantity_"+id).value;
	if(!rate[id].isInteger)
	{
		rate[id] = 0; 
		document.getElementById("rate_"+id).value = rate[id];
	}

	if(!quantity[id].isInteger())
	{
		quantity[id] = 0; 
		document.getElementById("quantity_"+id).value = quantity[id];
	}
	adding = quantity[id] * rate[id];
	document.getElementById("amount_"+id).innerHTML = adding;
	total += adding;
	document.getElementById("total").innerHTML = total;
}
</script>
</head>
<body>
<?php 
for($i=1;$i<=3;$i++)
{
?>
<input type="text" id='rate_<?php echo $i; ?>' onChange="updateValues(this.id);" /> * <input type="text" id='quantity_<?php echo $i; ?>' onChange="updateValues(this.id);" /> = <span id='amount_<?php echo $i; ?>' style="border: 2px solid black;padding:2px;"></span><br /><br />
<?php
}
?>
Total: <span id="total" style="border: 2px solid black;padding:2px;"></span>
</body>
</html>
This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.