0

I want to get html dom attribute and turn into JSON when submit the form.

Here is the html form element:

<div data-role="fieldcontain">
    <fieldset data-role="controlgroup" data-type="vertical" data-mini="true">
        <legend>1、question1?</legend>
        <input name="yes" id="checkbox5"
        type="checkbox">
        <label for="checkbox5">yes</label>
        <input name="no" id="checkbox16" type="checkbox">
        <label for="checkbox16">no</label>
    </fieldset>
</div>
<div data-role="fieldcontain">
    <fieldset data-role="controlgroup" data-type="vertical" data-mini="true">
        <legend>2、question2?</legend>
        <input name="below_60" id="checkbox9"
        type="checkbox">
        <label for="checkbox9">60</label>
        <input name="btw_60_80" id="checkbox13" type="checkbox">
        <label for="checkbox13">60-80</label>
        <input name="btw_80_100" id="checkbox14" type="checkbox">
        <label for="checkbox14">80-100</label>
    </fieldset>
</div>

And the JSON is like this:

[{
    {
        "question": "1、question1?",
        "ask": {
            ["type": "checkbox", "name": "yes", "value": "yes", "isChecked": 0], ["type": "checkbox", "name": "no", "value": "no", "isChecked": 1]
        }
    },{
        "question": "2、question2?",
        "ask": {
            ["type": "checkbox", "name": "below_60", "value": "60", "isChecked": 1], ["type": "checkbox", "name": "btw_60_80", "value": "60-80", "isChecked": 1], ["type": "checkbox", "name": "btw_80_100", "value": "80-100", "isChecked": 1]
        }
    }
 }]
Larsenal
  • 49,878
  • 43
  • 152
  • 220

2 Answers2

2

Looks like http://api.jquery.com/serialize/ might be able to help you out.

Ian Link
  • 684
  • 1
  • 8
  • 11
0

Try this:

$(function(){
    var data = [];
    $('fieldset').each(function(){
        var fieldset = $(this);
        var item = { question: fieldset.find('legend').text(), ask: [] };
        fieldset.find('input').each(function(){
            var input = $(this);
            item.ask.push({ type: input.attr('type'), name: input.attr('name'),
                        isChecked: input.is(':checked') ? '1' : '0',
                        value: fieldset.find('[for="' + input.attr('id') + '"]').text() });
        });
        data.push(item);
    });
    console.log(data);
});

Demo: http://jsfiddle.net/Qf3pX/

webdeveloper
  • 17,174
  • 3
  • 48
  • 47