Search code examples
apache-flexactionscript-3flex4flex4.5

How can call function in dynamic radio button?


I have created a quiz app using XML.

My XML code:

<item>
 <question type="singleChoice">
 <![CDATA[1.What does CSS stand for?]]>
 </question>
  <answer correct="yes">Cascading Style Sheets</answer>
  <answer>Computer Style Sheets</answer>
  <answer>Colorful Style Sheets</answer>
  <answer>Creative Style Sheets</answer>
</item>

and my flex Script code:

    protected function buildQuestion():void {
            var question:XML=XML(xmlList[quizIndex])
                answerOption.removeAllElements()
                if(question.question.@type == SINGLE_CHOICE)
                {
                    for each(var tempxml:XML in question.answer)    
                    {
                        var rad:RadioButton= new RadioButton();
                        rad.label=tempxml[0];
                        answerOption.addElement(rad);
                    }       
                }

How can I access the current radio button to validate this answer?

Example Image


Solution

  • You can use spark.components.RadioButtonGroup for that:

    protected function buildQuestion():void 
    {
        var question:XML = XML(xmlList[quizIndex]);
        answerOption.removeAllElements();
        if (question.question.@type == SINGLE_CHOICE)
        {
            var group:RadioButtonGroup = new RadioButtonGroup();
            group.addEventListener(Event.CHANGE, onAnswerChanged);
            for each(var tempxml:XML in question.answer)    
            {
                var rad:RadioButton = new RadioButton();
                rad.label = tempxml[0];
                rad.group = group;
                rad.value = tempxml[0];
                answerOption.addElement(rad);
            }       
        }
    }
    
    private function onAnswerChanged(event:Event):void
    {
        var group:RadioButtonGroup = RadioButtonGroup(event.currentTarget);
        trace ("Selected answer: " + group.selectedValue);
    }