0

I'm using jquery to make a simple quiz. I'm trying to get the question, answer (content) and answer (index) into an object. Here is my code so far and a fiddle.

    $('.submit').on('click', function() {

        $('li[data-question]').each(function(i){

            question = $(this).attr('data-question');
            answer = $(this).find('input:checked').parent().text().trim();
            index = $(this).find('input:checked').parent().parent().parent().index() + 1;

            $('body').data(question, {
                "question":question,
                "index":index,
                "answer":answer
            });

            console.log( $('body').data() );

        });

    });

http://jsfiddle.net/oe6z9svq/2/

That works, but I want to just get the final object of responses out of it. Currently it steps through each question and makes an object for each one, adding one at a time.

How can I return(?) the final result as json then use it elsewhere?

2
  • 1
    Stick everything into an Array when looping. Commented Aug 29, 2014 at 18:26
  • Got it working using your suggestion, but is there a way to get the last .data iterations object from the loop? Commented Aug 31, 2014 at 2:38

1 Answer 1

1

To expand on MelancialUK's comment to put all the questions in an array:

$('.submit').on('click', function () {

    var questions = [];

    $('li[data-question]').each(function (i) {

        question = $(this).attr('data-question');
        answer = $(this).find('input:checked').parent().text().trim();
        index = $(this).find('input:checked').parent().parent().parent().index() + 1;

        questions.push({
            question: question,
            index: index,
            answer: answer
        });

    });

    $('body').data("questions", questions);
    console.log(questions);

});

http://jsfiddle.net/oe6z9svq/3/

Sign up to request clarification or add additional context in comments.

1 Comment

I initially used an array, but thought that .data would be better. I restructured my code a little with your advice and got it to where it needs to be. Thanks a lot. Curiously, is there a way to do it with just .data? As in get the last iterations object?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.