Reputation: 13
I have 4 inputs in a form:
<form id="mark_date_form">
<input type="text" name="title" class="form-control" placeholder="Title" value="motherday">
<input type="text" name="date" class="form-control datepick" placeholder="MM/DD" value="05/13">
<input type="text" name="title" class="form-control" placeholder="Title" value="fatherday">
<input type="text" name="date" class="form-control datepick " placeholder="MM/DD" value="06/18">
</form>
When I use $('#mark_date_form').serializeArray()
in jQuery, it returns
[
{
"name": "title",
"value": "motherday"
},
{
"name": "date",
"value": "05/13"
},
{
"name": "title",
"value": "fatherday"
},
{
"name": "date",
"value": "06/18"
}
]
The question is I have to come out with something like this:
[
{
"title": "motherday",
"date": "05/13"
},
{
"title": "fatherday",
"date": "06/18"
}
]
What should be the jQuery looks like?
Thank you very much!
Upvotes: 1
Views: 101
Reputation: 997
I think you are looking for this $("#mark_date_form").serialize()
;
Update: sorry for the @daniel-cai is correct.
Use $("#mark_date_form").serializeArray();
for getting JavaScript literal object.
Upvotes: 6
Reputation: 3545
Simple way to get a json file as you want is:
var o = {};
$("#mark_date_form").serializeArray().map(function(x){o[x.name] = x.value;});
console.log(o);
Result:
Object {title: "motherday", date: "05/13"}
DEMO: http://jsfiddle.net/gon250/s3xerkgc/1/
Hope it's helps.
Upvotes: 0
Reputation: 9430
You can use this:
var a = [];
$('#mark_date_form input').each(function(){
if($(this).attr('name')=='title'){
a.push({"title":$(this).val(),"date":$(this).next().val()});
}
});
console.log(a);
Output:
[Object { title="motherday", date="05/13"}, Object { title="fatherday", date="06/18"}]
Upvotes: 0