NeedHate NeedHate - 5 months ago 7
jQuery Question

How to get each of objects in list on click

I have list of questions.
And I have a html, f.e., . Each click, changes html ".title" with a next question from objects.
Click on button, I get: "Is it good to be me?",
next click, I get: "Who is the best man?" and so on...



var questions = {
first: "Is it good to be me?",
second: "Who is the best man?",
third: "Do you believe?",
fourth: "Are you sexy?"
};
var txt = "";
var x;

for(x in questions) {
txt += questions[x] + "<br>";
console.log(txt)
}




Answer

You can use array instead of object.

var questions = [
    "Is it good to be me?",
    "Who is the best man?",
    "Do you believe?",
    "Are you sexy?"
];

var index = 0;
$("button").click(function(){
    $("div").text(questions[index]);
    index++;
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div></div>
<br/>
<button>Get question</button>

To getting index of question, use index variable. Also you can use data-index attribute to do this.