rangeslider test

http://rangeslider.js.org/ testing with dynamic adding of input elements

by Kyle Falconer

HTML

<script src="https://code.jquery.com/jquery-1.12.0.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/rangeslider.js/2.1.1/rangeslider.min.js"></script>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/rangeslider.js/2.1.1/rangeslider.min.css">
<div id="questions_wrapper"></div>

CSS

.question.range label {
  display: block;
  text-align: center;
  width: 200px;
  height: 40px;
  margin: 40px 0 5px 0;
}

.question.range input[type="range"],
.question.range .rangeslider {
  float: none;
  display: inline-block;
  width: 200px;
}

.question.range .right,
.question.range .left {
  display: inline-block;
  width: 40px;
  height: 40px;
  margin: 5px;
  text-align: center;
}

JavaScript

var data = [{
  "question_text": "A or B?",
  "choices": [
    "A",
    "B"
  ],
  "type": "range",
  "scale": [
    1,
    5
  ]
}, {
  "question_text": "B or C?",
  "choices": [
    "B",
    "C"
  ],
  "type": "range",
  "scale": [
    1,
    5
  ]
}];
var answer_index = 0;
var question_index = 0;

function addRangeQuestion(o) {
  var qid = o.id;
  var question = o.question_text;
  var answers = o.choices;
  var input_vals = {
    'min': o.scale[0],
    'max': o.scale[1],
    'step': 1
  };

  if (answers.length !== 2) {
    W.console.warn('Malformed question: need two and only two answers for a "range" question.', o);
    return;
  }

  var $frag = $(document.createDocumentFragment());
  var $q_wrapper = $('<div class="question range"/>');

  $('<label>').attr({
    for: 'a_' + answer_index
  }).text(question).appendTo($q_wrapper);

  var $left_option = $('<div>').addClass('left').text(answers[0]).appendTo($q_wrapper);

  var $right_option = $('<div>').addClass('right').text(answers[1]);

  var dl_id = 'q_' + question_index + '_dl';
  $('<input type="range"/>').attr({
    id: 'a_' + answer_index,
    name: qid,
    required: true,
    min: input_vals.min,
    max: input_vals.max,
    step: input_vals.step,
    value: input_vals.min + (input_vals.max - input_vals.min) / 2
  }).appendTo($q_wrapper);



  $right_option.appendTo($q_wrapper);

  answer_index += 1;
  question_index += 1;

  $frag.append($q_wrapper);
  $frag.appendTo(questions_wrapper);
}

function set(response) {
  response.forEach(function(e) {
    // var type = input_types[e.type];
    var type = e.type;
    if (type === "range") {
      addRangeQuestion(e);
    }
  });
  $('input[type="range"]').rangeslider({
  	polyfill: false
  });
}

(function init() {
  questions_wrapper = document.getElementById('questions_wrapper');
  set(data);
})();