Sam Sam - 4 months ago 9
HTML Question

How does jQuery dynamic content work?

I don't know if that's what it's called but I'm trying to make some kind of interactive page that changes content based on a series of questions that the user can answer with "Yes" or "No".
Here's a simplified version of the code for better understanding.

HTML:

<div class="container">
<h1>Some question?</h1>
<h2 id="yes" role="button">Yes</h2>
<h2 id="no" role="button">No</h2>
</div>


jQuery:

$(function() {
var question = $("h1");
var yes = $("#yes");
var no = $("#no");

$(yes).click(function() {
question.text("Some text. Some other question?");
});

$(yes).click(function() {
question.text("Different text. Different question?")
});

});


Now what I want to do is: If the user's answer to the first question (the one in the HTML) was "yes" then it would display the second question (the first one in jQuery) and if his answer to that was "yes" it'd display the next question and so on. But what it does is just jump to the last question specified in jQuery when the user clicks "yes".

How do I control that? Is that the wrong way to go about what I'm trying to achieve? I'm a noob so sorry if not making much sense.

Edit: Now how do I write an if statement that will
$("<img src="#">).appendTo(container);
when the user reaches the third question?

Answer
$(function() {
    var count = 0;
    var question = $("h1");
    var yes = "#yes";
    var no = "#no";
    var questions = [
                      "Some text. Some other question?",
                      "Different text. Different question?"
                    ];

    $(yes).click(function() {
        if(count == 2){
            $("<img src='#'>").appendTo(container);
        }
        question.text(questions[count]);
        count++;
    });   
});

Try this code.

When u call

$(yes).click(function() {
        question.text("Some text. Some other question?");
    });

$(yes).click(function() {
        question.text("Different text. Different question?")
    });

After executing the first $(yes).click, it continues to execute the 2nd $(yes).click, hence the issue you are facing.

My suggested approach is to put populate all ur "questions" into an array, and then use an index count to populate the <h1> tag