Dirk-Jan
Dirk-Jan

Reputation: 1149

Javascript/Jquery loop elements

I am trying to make a quiz for a school a friend of mine works. The students get to see 4 word and 4 sentences and they need to drag the right word to the sentence that fits with it.

I am making this inside the browser with jQuery and MySQL, this so that the teacher is able to view who did the assignment and who didn't.

The teacher want's to have 4 questions per page and then you click the next button and you see what you did wrong/good and move on to the next 4 questions. At the end I need to write it to the database.

Currently I am walking through the answer with the following jQuery code.

 if ($("#answer1").data("answer") == $("#question1").text()) {
   $("#question1").css("background","#0F9");
   good++;
 } else {
   $("#question1").css("background","#903");
   mistakes++;
 };

I was thinking about loading all the questions at once and hiding/showing them when you click the next button to prevent double questions and to make it easy to remember the good/wrong answers.

Now I want to make the looping through the code above dynamic. So I though about putting it in a for look like this.

 for (var i = 0; i < 4; i++) {
   if ($("#answer" & (i+page)).data("answer") == $("#question" & (i+page)).text()) {
     $("#question" & (i+page)).css("background","#0F9");
     good++;
   } else {
     $("#question" & (i+page)).css("background","#903");
     mistakes++;
   }; 
 }

Ofcourse the & (i+page) part isn't working at all. (the page increases when you hit the next button by 4). Is there some way to make this possible in javascript/jQuery or do I need to chance my approach completely?

Upvotes: 0

Views: 70

Answers (2)

Paul S.
Paul S.

Reputation: 66334

String concatenation in JavaScript is done with the + operator. The & is a bitwise AND.

JavaScript also has

'foo' + 0; // "foo0" i.e. String + Number = String
0 + 'foo'; // "0foo" i.e. Number + String = String

Upvotes: 2

Niet the Dark Absol
Niet the Dark Absol

Reputation: 324640

Replace all & with + in the code you gave.

Upvotes: 4

Related Questions