Add or remove row from client input and store them in an object

Add or remove row from client input and store them in an object

metadevmetadev Posts: 17Questions: 6Answers: 0

Hello. I am trying to implement a dynamic table where I can add or remove row based on button clicks. I have implemented a basic working example here https://live.datatables.net/tagigike/2/edit

What I am looking for is
1. When I enter the input fields and click on the Add Row button, I want to insert a row in the bottom table (table with id arrTable)
2. When I select row(s) from the bottom table (table with id arrTable) and click on the Delete row button, I want to remove said selected rows
3. Finally, when I click on the Save as draft button, I want to console.log the object arrearToSave which would be in the format

{
  empDetail: {
    ein: "",
    name: ""
  },
  arrearDetail: [
    { 
      month: "", 
      year: "" 
    },
    // multiple objects based on multiple selections
  ]
}

This question has an accepted answers - jump to answer

Answers

  • kthorngrenkthorngren Posts: 20,425Questions: 26Answers: 4,794
    Answer ✓

    When I enter the input fields and click on the Add Row button, I want to insert a row in the bottom table (table with id arrTable)

    Since you have defined columns.data Datatables expects the row data in object form, not array. See the updated example.

    When I select row(s) from the bottom table (table with id arrTable) and click on the Delete row button, I want to remove said selected rows

    Looks like you want to use the select extension. I added the select library to the example.

    When using the select extension use the selector-modifier of {selected: true} to get the selected rows.

    Finally, when I click on the Save as draft button, I want to console.log the object arrearToSave which would be in the format

    Chain toArray() to convert the API result into a standard array. Optionally you could use row() instead of rows() with var payloadEmp = dataEmp[0] to get only the first element. And use the selector-modifier of {selected: true}.

    Updated example:
    https://live.datatables.net/tagigike/4/edit

    Kevin

  • kthorngrenkthorngren Posts: 20,425Questions: 26Answers: 4,794

    I removed the dataList parameter from the second table and just initialized it empty. If you want to put it back you can. Might be better to pass an empty array rather than null but null seems to work. Unless you plan to change the Datatable configuration you normally won't want to use destroy, instead use clear() to clear the table with rows.add() to add new rows.

    Kevin

  • metadevmetadev Posts: 17Questions: 6Answers: 0

    @kthorngren I tried with just HTML and js before but figured I might have more complex procedures in future and decided to go with datatables. Nevertheless, thank you so much.

Sign In or Register to comment.