jquery - form to json in specific output in javascript -
i have form like:
<form> <div id="studentlist"> <div class="studentrow"> <input name="first" type="text" placeholder="first name"> <input name="last" type="text" placeholder="last name"> </div> <div class="studentrow"> <input name="first" type="text" placeholder="first name"> <input name="last" type="text" placeholder="last name"> </div> <div class="studentrow"> <input name="first" type="text" placeholder="first name"> <input name="last" type="text" placeholder="last name"> </div> </div> <input id="send" value="submit" type="submit"> </form>
and json in format:
{"students":[ {"first":"john", "last":"doe"}, {"first":"anna", "last":"smith"}, {"first":"peter", "last":"jones"}, ]}
i tried use jquery.serializejson , call with:
$('#form').submit(function() { console.log( $('#form').serializejson() ) ; return false; });
but is:
object { first: "peter", last: "jones" }
any hint how configure plugin?
thanks in advance!
this solution think easier php...
first, format html correctly:
<form> <div id="studentlist"> <div class="studentrow"> <input name="students[0][first]" type="text" placeholder="first name"> <input name="students[0][last]" type="text" placeholder="last name"> </div> <div class="studentrow"> <input name="students[1][first]" type="text" placeholder="first name"> <input name="students[1][last]" type="text" placeholder="last name"> </div> <div class="studentrow"> <input name="students[2][first]" type="text" placeholder="first name"> <input name="students[2][last]" type="text" placeholder="last name"> </div> </div> <input id="send" value="submit" type="submit"> </form>
then javascript array format you're looking for:
var x = $("#studentlist").find('input:last').attr('name').match(/^students\[([\d]+)\]/)[1]; var ary = []; var obj = {}; for(var = 0; i<=x; i++){ ary.push({first: $("input[name='students["+i+"][first]']").val(), last: $("input[name='students["+i+"][last]']").val()}); } obj = { students: ary }; console.log(json.stringify(obj));
Comments
Post a Comment