PDA

View Full Version : Resolved Binding issue with add event



mattyod
10-03-2008, 01:32 PM
Hi,

I'm in a bit of a bind over passing an index of an item through an add event function (please forgive the pun).

The add event function is a slight adaptation of one that I borrowed and have been using for some time.

In simplified form what I have is:

1: a list of options in the HTML:



<select id="test">
<option value="item 1">item 1</option>
<option value="item 2">item 2</option>
<option value="item 3">item 3</option>
</select>


2: a script that iterates through an array of the options and attaches an event to each of them which should in turn call a function using the count variable of the loop like so:



function fAddEvent(sObject, sEventType, sFunction){
if (sObject.addEventListener){
sObject.addEventListener(sEventType, sFunction, false);
return true;
} else if (sObject.attachEvent){
var sReturn = sObject.attachEvent("on" + sEventType, sFunction);
return sReturn;
} else {
return false;
}
}

function fTest(nNumber) {
alert(nNumber);
}

function fBindingControl() {
var aOptions = document.getElementById('test').getElementsByTagName('option');
var nLength = aOptions.length;
for (nCount = 0; nCount < nLength ; nCount++) {
fAddEvent(aOptions[nCount], 'click', function() {fTest(nCount);});
}
}

fAddEvent(window, 'load', fBindingControl);


The trouble I'm having is that my binding seems to get lost with nCount and in the sample above everything has a value of 3 (the last nCount).

I've tried "apply," I've tried "eval", I've tried "this", I've tried "[nCount]"; I've also tried just about every combination of the above but in all cases I seem to just get either "undefined" or "3" returned.

Is my logic way off or can you help me with my syntax please?

vwphillips
10-03-2008, 03:15 PM
accepting IE cannot attach events to options


function fBindingControl() {
var aOptions = document.getElementById('test').getElementsByTagName('option');
var nLength = aOptions.length;
for (nCount = 0; nCount < nLength ; nCount++) {
aOptions[nCount].nu=nCount;
fAddEvent(aOptions[nCount], 'click', function() {fTest(this.nu);});
}
}

mattyod
10-03-2008, 04:34 PM
Aha that does the trick.

A bit of a spanner in my works that IE won't accept events on an option, which I suppose kinda makes sense. But seeing as in the actaul version of my code I'll be using an array of selects as well the solution still holds water for me :thumbsup:

Any chance you could point me at something to read that explains exactly what's going on in your answer there?