How to use jquery each of HTML dom and get attribute in JSON

I want to get the html dom attribute and go to JSON when submitting 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 JSON looks 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] } } }] 
0
json javascript jquery dom
Oct 10
source share
2 answers

Try the following:

 $(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/

0
Oct 10 '12 at 17:35
source share
— -

It looks like http://api.jquery.com/serialize/ can help you.

+2
Oct. 10
source share



All Articles