jquery - What are good ways for creating JSON to store checked checkbox options? -
the code below creates json string checked response options. wanted link checked response options ids question ids , allow several response options included. if 2 options chosen json string looks {"question0":["options0","options1"]}. code below works, however, i'd know whether there more compact, cleaner ways want. code style ok or can improved? thanks
html layout
<div id="survey"> <div id="question0" class="question">enter question <br> <input id="options0" class="options-ready" type="checkbox"> <label class="opt-label">yes</label> <br> <input id="options1" class="options-ready" type="checkbox"> <label class="opt-label">no</label> <br> </div> <div id="question1" class="question">enter question <br> <input id="options2" class="options-ready" type="checkbox"> <label class="opt-label">yes</label> <br> <input id="options3" class="options-ready" type="checkbox"> <label class="opt-label">no</label> <br> <input type='button' class='survey-submit' value='submit'> </div> </div>
js code goes here:
$(function() { $(".survey-submit").click(function () { function checked(target) { var arr = []; target.each(function () { if ($(this).prop("checked")) { arr.push($(this).attr("id")); } else { return null; } }); return arr; } $(".question").each(function () { var obj = {}; obj[$(this).attr("id")] = checked($(this).children(".options-ready")); var json = json.stringify(obj); }); }); });
Comments
Post a Comment