-2

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)
}
NeedH8
  • 472
  • 6
  • 21

2 Answers2

2

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.

Mohammad
  • 21,175
  • 15
  • 55
  • 84
-1

You can try:

for(x in questions) {
    txt += questions[x] + "\n";
}
console.log(txt)
ThiepLV
  • 1,219
  • 3
  • 10
  • 21