I run a web site on which subscribing members can advertise holiday accommodation etc. The amount a member pays depends (in part) on the number and type of their properties. In the 'Members Area' (which requires login) a member can see how much their subscription for this year and next year will be. The appropriate year is selected by the member clicking a button. The data is all extracted from a MySQL database.

Hitherto this has always required a page refresh, but I have been trying to introduce a bit of Ajax, so that only the table gets refreshed. It's all working very well as long as the 'onclick' event handlers are hard coded. I have been trying to assign the onclick event handlers dynamically, but always run into a problem that BOTH the event handlers take on the final value of the variable (k+i) (which should be the year, 2012 or 2013, but always ends up as 2014).

	function prepareHandler() {
		if (!document.getElementById) return;
		var inputs = document.getElementsByTagName('input');
		var len = inputs.length;
		var k = 2012;
		for (var i=0; i<len; i++) {
			var trhd = (k+i);
			inputs[i].onclick = function() {setRateId(k+i);};
			alert ("Year = " + (k+i)); // when function runs, shows correct values, 2012, 2013
		alert ("final Year = " + (k+i)); // Always 2014 (which I think is to be expected)

	function setRateId(abcd) {
		alert ("setRateid called; year = " + abcd); // ALWAYS shows 2014 (unless event handlers are hard-coded)
		var url = "subsformlogic.php?rateid=" + abcd;
		return !grabFile(url);


	window.onload = prepareHandler; // disabled when using hard coded event handlers
It's as though the values set by the line
inputs[i].onclick = function() {setRateId(k+i);};
aren't being 'frozen', but continue to increment. Surely this should not happen ?

If I use hard coded event handlers there's no problem at all (the PHP variables evaluate to 2102 and 2013 respectively):-

HTML Code:
<p><input type="button" value='This Year' onclick='setRateId(<?php echo $thisyear; ?>)' />
<input type="button"  value='Next Year' onclick='setRateId(<?php echo $nextyear; ?>)' />
In this case there are only two event handlers required, so hard coding them is no hardship. However I'm looking to make similar changes to other pages, where there will be more.

I think the problem must lie in the function 'prepareHandler' as 'setRateId' runs OK even though it gets duff input (there's an error message if the year exceeds 2013).

Have I overlooked something very basic ?