PDA

View Full Version : Add Event Listener to Multiple Checkboxes


AmyCohen
09-21-2009, 08:13 PM
Hello! This is my first post in a programming forum, so I apologize in advance for any (unintentionally!) bad forum etiquette.

I've written a loop using ActionScript that automatically creates checkboxes. The checkboxes are created and displayed just fine. The problems begin when I try to add an event listener to each individual checkbox that's established within the loop. For some reason, the only target that is received by the function that is called by the event listener is the last checkbox established in the loop. Here is a snippet from my code:


for (var m:Number = 0; m < numLayers; m++){
var check:CheckBox = new CheckBox();
check = checkArray[m];
legend.addChild(check);
check.name = "check" + ((m + 1).toString());
trace(check);

check.addEventListener(Event.CHANGE, function (e:Event):void{
trace(check);
addPolyLayer(check);
});
}
Any advice would be greatly appreciated!

-Amy-

0404kumar37
09-22-2009, 05:31 AM
Hi is this what you are looking for?


<?xml version="1.0" encoding="utf-8"?>
<mx:Application xmlns:mx="http://www.adobe.com/2006/mxml" layout="vertical"
creationComplete="init()">

<mx:Script>
<![CDATA[
import mx.containers.VBox;
import mx.controls.CheckBox;

private var checkArra:Array = new Array();

private function init():void
{
for (var m:Number = 0; m < 10; m++)
{
var vb:VBox = new VBox()
addChild(vb);
var check:CheckBox = new CheckBox();
check.label = "check" + ((m + 1).toString());
vb.addChild(check);
check.name = "check" + ((m + 1).toString());
check.addEventListener(Event.CHANGE, testChange);
}
}

private function testChange(event:Event):void
{
for(var i:int = 1; i<=10;i++)
{
if(event.currentTarget.name == "check"+i.toString())
{
trace("you have clicked check" +event.currentTarget.name)
}

}
}

]]>
</mx:Script>

</mx:Application>

AmyCohen
09-23-2009, 01:59 PM
Yes! :)