1

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!

captainsac
2,4903 gold badges29 silver badges51 bronze badges
asked May 25, 2015 at 9:08

3 Answers 3

6

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.

answered May 25, 2015 at 9:10
Sign up to request clarification or add additional context in comments.

2 Comments

great answer. +1, very fast.
Thank you for answer, this will return title=motherday&date=05%2F13&title=fatherday&date=06%2F18
0

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"}]
answered May 25, 2015 at 9:15

Comments

0

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.

answered May 25, 2015 at 9:25

Comments

Your Answer

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

By clicking "Post Your Answer", you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.