Akshay
Akshay

Reputation: 391

Get form data in JSON format for multiple fields of same name

Hello I am building a form table which have multiple same names for the rows. I want to submit the form table in JSON format where I am using a plugin. Link - Serialize JSON form plugin

with $("#form").serializeJSON();. With this I am only getting the last field in JSON format. It is replacing all the fields with the same name and have replaced it with the last field.

I wish to show all the fields in JSON format. For eg -

[
    {
        "field1": "id1",
        "field2": "dsda",
        "field3": "dsda",
    },
    {
        "field1": "id2",
        "field2": "dsda",
        "field3": "dsda",
    },
    {
        "field1": "id3",
        "field2": "dsda",
        "field3": "dsda",
    },
]

Instead I am only getting -

[
    {
        "field1": "id3",
        "field2": "dsda",
        "field3": "dsda",
    },
]

Here is my code -

$("#button").click(function() {
  var jsonForm = $("#form").serializeJSON();
  console.log(jsonForm);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery.serializeJSON/2.9.0/jquery.serializejson.min.js"></script>
<form id="form" method="post" action="otherpage.html">
  <table>
    <thead>
      <tr>
        <th>Field 1</th>
        <th>Field 2</th>
        <th>Field 3</th>
      </tr>
    </thead>
    <tbody>
      <tr>
        <td><input type="text" name="field1" value="id1"></td>
        <td><input type="text" name="field2" value="dsda"></td>
        <td><input type="text" name="field3" value="dsda"></td>
      </tr>
      <tr>
        <td><input type="text" name="field1" value="id2"></td>
        <td><input type="text" name="field2" value="dsda"></td>
        <td><input type="text" name="field3" value="dsda"></td>
      </tr>
      <tr>
        <td><input type="text" name="field1" value="id3"></td>
        <td><input type="text" name="field2" value="dsda"></td>
        <td><input type="text" name="field3" value="dsda"></td>
      </tr>
    </tbody>
  </table>
  <button type="button" name="button" id="button">Serialize</button>
</form>

Upvotes: 1

Views: 1779

Answers (1)

AwesomeGuy
AwesomeGuy

Reputation: 1089

You cannot have two or more fields with the same name in one form, instead you need to tell the html it's an array by adding [] at the end of the name for each same name, for example

<tr>
    <td><input type="text" name="field1[]"></td>
    <td><input type="text" name="field2[]"></td>
    <td><input type="text" name="field3[]"></td>
</tr>
<tr>
    <td><input type="text" name="field1[]"></td>
    <td><input type="text" name="field2[]"></td>
    <td><input type="text" name="field3[]"></td>
</tr>

Upvotes: 2

Related Questions