There is a questionnaire interface that works without reloading the page and the data that is taken from the json file. The variant with one question is realized, the difficulties begin when there are many questions in the chain one by one. How to do so, to read data from a json file into an array and consistently give after pressing the button to answer the next question?

I collect an array through

 data.forEach(function(item) {}); 

, but if you put the answers function inside , then absolutely all the answers waiting for different questions will simply be displayed on the same page. How can you realize your plans?

Fiddle here - http://jsfiddle.net/qxrognd6/

 $(function() { var vote = {}; $('#ok').click(function() { $.get(poll.json, function(data) { // фактически данные poll.json хранятся в таком виде //data = [{"id":"1", "question":"Какую марку предпочитаете?", "answers":["honda", "bmw", "volvo"]}, {"id":"2", "question":"Цвет авто?", "answers":["black", "red", "blue"]} data.forEach(function(item) { vote.id = item.id; vote.question = item.question; vote.answers = item.answers; }); answers(); }); appearance('#start', '#content'); return false; }); var appearance = function(slide, content) { $(slide).hide('fast', showNewContent); $('#load').remove(); $('#wrapper').append('<span id="load">LOADING...</span>'); $('#load').fadeIn('normal'); function showNewContent() { $(content).show('normal', hideLoader()); } function hideLoader() { $('#load').fadeOut('normal'); } }; var answers = function() { var form = $('#vote'); var answers = form.find('.answers'); form.parent().find('.question').text(vote['question']); for (var i = 0; i <= vote['answers'].length - 1; i++) { answers.append('<div class="radio">' + '<label>' + '<input type="radio" name="poll" value="' + (i + 1) + '">' + vote['answers'][i] + '</label>' + '</div>'); } }; }); 
 #content { display: none; } #load { display: none; position: absolute; right: 10px; top: 10px; width: 43px; height: 11px; text-indent: -9999em; } 
 <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <div id="start"> <a id='ok' href=''>Поехали</a> </div> <div id="content"> <h4 class="question">Вопрос</h4> <form id="vote" action="vote.php" method="POST"> <div class="answers"></div> <button type="submit" class="btn btn-default">ответить</button> </form> </div> 

  • one
    What do you have answers in the answers function? - mix
  • one
    I mean, that's answers.append('<div class="radio">... - mix
  • @mix oh, I apologize, did not add 3 lines of code. corrected - Vasya
  • var answers = function() { and answers.append( - what are the answers ? - Igor
  • @Igor eh, do you mean the name of the function? var answers = function() {} is a function of answers to a question that is called to each, and answers.append( are the string variables themselves that are appended to the form itself. I hope it will be clearer - Vasya

0