2

How to serialize those array input using jquery to

<form id="myform" action="" method="">
    <input type="text" name="name[0].basketball">
    <input type="text" name="name[0].ball">
    <input type="text" name="name[1].basketball">
    <input type="text" name="name[1].ball">
</form>

Something looks like this:

[{basketball: 'TestBasketball', Ball: 'TestBall'}, {basketball: 'TestBasketball1', Ball: 'TestBall2'}]

JQuery (This code not working, it just get name[0].basketball: 'TestBasketball')

$('#myform').serializeArray();
3
  • serializeArray() cannot give you the output you require. To get that you'd need to build the array manually. I'd suggest looking in to map() Commented Nov 20, 2018 at 15:41
  • yes im going to post it to my controller. but I don't know why it is not working if i use serialize() Commented Nov 20, 2018 at 15:46
  • 2
    Don't use dot notation then ... use name[0][basketball] format and serialize Commented Nov 20, 2018 at 15:46

1 Answer 1

2

Something like this?

var ser = [];
$("#myform>input[type=text]").each(function() {
  var idx = parseInt(this.name.split("[")[1]);
  var key = this.name.split(".")[1];
  if (ser[idx]) ser[idx][key]=this.value;
  else ser.push({[key]:this.value});
});
console.log(ser);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form id="myform" action="" method="">
  <input type="text" name="name[0].basketball" value="TestBasketball1" />
  <input type="text" name="name[0].ball" value="TestBall1" />
  <input type="text" name="name[1].basketball" value="TestBasketball2">
  <input type="text" name="name[1].ball" value="TestBall2" />
</form>

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

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.