简体   繁体   中英

create json from form

Here is my form: http://jsfiddle.net/sxGtM/4743/ ... when you submit this form I need create JSON like this

data = {
        'voted_questions': [question.pk, question.pk, question.pk, question.pk],
        'answers': [
        {
        'question': question.pk,
        'option': option.pk,
        },
        {
        'question': question.pk,
        'option': option.pk,
        },
        ]
    }

question.pk and option.pk are numbers which identifying each question and option (it is ID). Could you help me how can I create this JSON?

I'm not 100% sure why you want a list of answered questions, when you also have a list of answers (which includes the question IDs). It's what you asked for though, so here you go.

HTML

<h2>Form</h2>
<form action="" method="post">
Which city is in Great Britain?<br/>
<input type="hidden" name="first" value="1"/>
London:<input type="radio" name="first" data-questionid="1" value="11"/><br/>
New York:<input type="radio" name="first" data-questionid="1" value="12"/><br/>
Which city is in USA?<br/>
<input type="hidden" name="second" value="2"/>
Washington:<input type="radio" name="second" data-questionid="2" value="13"/><br/>
Tokio:<input type="radio" name="second" data-questionid="2" value="14"/><br/>
<p><input type="submit" /></p>
</form>
<h2>JSON</h2>
<pre id="result">
</pre>

Javascript

$(function() {
    $('form').submit(function() {
        var voted_questions = [];
        var answers = [];

        $('input[type="radio"]:checked').each(function(){
            voted_questions.push($(this).data('questionid'));
            answers.push({'question':$(this).data('questionid'), 'options':this.value});
        });

        var data = {
            'voted_questions': voted_questions,
            'answers': answers
        };

        $('#result').text(JSON.stringify(data));
        return false;
    });


});

jsfiddle

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM