dynamically buiding radio buttons

0 views
Skip to first unread message

Techno~

unread,
Feb 20, 2008, 10:47:02 AM2/20/08
to Ruby on Rails: Spinoffs
Hi, I'm new to prototype, only picked it up yesterday.

I have requirement to build on a online quiz based off an xml file.

My problem is when i try to create the radio buttons options. When I
concatenate my html for output I am not getting anything. If I don't
concatenate then I get the last iterated value (as expected).

I have converted the xml to JSON (which also caused me huge issues as
the evalJSON() function wasn't returning any output so I had to
incorporate the xml2json code)

code snippet:

if (quizJSON.quiz.questions.question[0].type == "multi") {
for
(x=0;x<quizJSON.quiz.questions.question[0].choices.choice.length;x++)
{
rb += '<label for="choice' + x + '"><input type="radio"
name="choices" id="choice' + x + '" value="' + x + '" />' +
quizJSON.quiz.questions.question[0].choices.choice[x] + '</label><br /
>';
alert(rb);
$('choices').update(rb)
};

Is ther a better way of achieving this?

Thanks


kangax

unread,
Feb 20, 2008, 11:07:14 AM2/20/08
to Ruby on Rails: Spinoffs
You could take advantage of Template/interpolation power.


var question = quizJSON.quiz.questions.question[0],
type = question.type,
choice = question.choices.choice,
rb = '';

var template = new Template('<label for="choice#{i}"><input
type="radio" name="choices" id="choice#{i}" value="#{i}" />#{content}</
label><br />');

if (type == "multi") {
choice.each(function(item, index) {
rb += template.evaluate({ i: index, content: item })
})
}

$('choices').update(rb);

Makes code look much more readable, imho.


Best,
kangax

Techno~

unread,
Feb 20, 2008, 11:34:34 AM2/20/08
to Ruby on Rails: Spinoffs
Hi,

thanks for the swift response. I *think* I understand what you have
given me.

To be honest I am only just coming back to web development and JS
after several years away and JS seems to have evolved massively, its
nothing like the simple 'rollover'/form validation that I last used.

I think I have a steep learning curve ahead of me.

thanks,
Techno~
Reply all
Reply to author
Forward
0 new messages