Angelos Chalaris Angelos Chalaris - 5 months ago 19
Javascript Question

Missing elements when randomizing order of list items in page

I am trying to develop a little test for an educational website and I want to randomize the order of the questions and exercises and later down the line the order of the answers under each question with a set of radio buttons. I have tried the code I found on two separate questions (namely this one and this one), although both the answers were practically the same. The code that I am using does what I want to some extent, but parts of my test are missing sometimes (most of the time I get 5 questions and 2-3 exercises instead of 6 and 4). How do I correct this? Full code sample in this JSFiddle (some irrelevant things from back-end are there, ignore them - content is placeholder to make debugging easier), as well as the javascript/jQuery code on its own below:

$(document).ready(function () {
var questions = $('.question');
for (var i = 0; i < questions.length; i++) {
var target = Math.floor(Math.random() * questions.length - 1) + 1;
var target2 = Math.floor(Math.random() * questions.length - 1) + 1;
questions.eq(target).before(questions.eq(target2));
}

var exercises = $(".exercise");
for (var j = 0; j < exercises.length; j++) {
var target = Math.floor(Math.random() * exercises.length - 1) + 1;
var target2 = Math.floor(Math.random() * exercises.length - 1) + 1;
exercises.eq(target).before(exercises.eq(target2));
}
});


P.S. #1: The website's back-end is built with Asp.Net and C#, if that has anything to do with the problem.

P.S. #2: Run the fiddle four or five times and count the number of questions and exercises to reproduce the problem.

Answer

I changed your code so that target will not be same as target2:

JavaScript

var questions = $('.question');
for (var i = 0; i < questions.length; i++) {
  var target = Math.floor(Math.random() * questions.length - 1) + 1;
  var target2 = target;
  while(target2 === target) {
    target2 = Math.floor(Math.random() * questions.length - 1) + 1;
  }
  questions.eq(target).before(questions.eq(target2));
}

var exercises = $(".exercise");
for (var j = 0; j < exercises.length; j++) {
  var target = Math.floor(Math.random() * exercises.length - 1) + 1;
  var target2 = target;
  while(target2 === target) {
    target2 = Math.floor(Math.random() * exercises.length - 1) + 1;
  }
  exercises.eq(target).before(exercises.eq(target2));
}

fiddle