sn0wy
sn0wy

Reputation: 69

How to switch questionnaire images in javascript

I have a semi-functional questionnaire. Initially a question appears with answers underneath, when an answer is clicked, the it is recorded and shown below to the user.

I now need help getting it so that when an answer from question 1 is hit the images of question 2, and its relative answers, appear in place of question 1 and its possible answers.

I have uploaded the entire thing on jsfiddle here http://jsfiddle.net/QV5EB/, I looked around for similar events, I found this piece of coding which seems relative to what I'm looking for, only it's based on captions which I am not using in my code.

self.selectQuestion = function(answer) {
    self.progress.push({
        question: questions[currentQuestionIndex].caption,
        answer: answer.caption
    });

Can anyone recommend a particular way of doing this?

Upvotes: 2

Views: 94

Answers (1)

Ben
Ben

Reputation: 57318

This should be pretty easy - set up IDs for the picture and each of the answers, and then just use document.getElementById() to grab each element.

For the picture, change its .src property to the URL of the new picture.

For the answers, change their .innerHTML property to the values of the new answers.


Your HTML might look like this:

<img src='whatever.jpg' id='pic'>
<label id='answer1'><input type='radio' name='answer' value='dog'> Dog</label>
<label id='answer2'><input type='radio' name='answer' value='pig'> Pig</label>
<label id='answer3'><input type='radio' name='answer' value='snake'> Snake</label>

Then, your JS might look like this:

document.getElementById('pic').src = 'newpic.jpg';
document.getElementById('answer1').innerHTML = '<input type='radio' name='answer' value='rooster'>Rooster';

etc.


There's a more elegant way to do it without .innerHTML, which is the DOM functions. Do some research on those, they're fun and powerful. In particular, the above JS might take the form

var rad = document.createElement('input');
rad.type = 'radio';
rad.name = 'answer';
rad.value = 'rooster';

...and maybe insert a span for the text, but it's a little overdoing it. Maybe innerHTML is best. :)

Upvotes: 2

Related Questions