How do you add an ID to a new row () using t.row.add

How do you add an ID to a new row () using t.row.add

koniahinkoniahin Posts: 186Questions: 39Answers: 7

This seems simple enough, but I cannot find a live example. My table is populated from a MySQL query. In the created table I add the MySQL ID to each row, something like:

<tr id="999">
  <td>cell 1 data</td>
  <td>cell 2 ...</td>
  <td>cell 3 ...</td>
</tr>

I do a mysql query to obtain the next available ID and set this as a variable in my jQuery code and set up an increment option in case of multiple rows added. The relevant code looks like:

    $(document).ready(function() {
      var t = $('#example').DataTable();

      var clicks = -1;
      $("#addRow").click(function(){ clicks++;});

      $('#addRow').on( 'click', function () {

        var ADD = "yes";
        var nextid= <?php echo $nextID; ?>;
        nextid = nextid + clicks;

        t.row.add( [
          // COMMENT - need function here to add row id as <tr id="999"> //
          '<input name="ck" onchange="selectUnselect(this.checked)" type = "checkbox" />',
          '<input type="text" name="name" value="<?php echo $name; ?>">',
          '<input type="text" name="position" value="<?php echo $position; ?>">',
        ] ).draw( false );

        var dataString = 'add='+ADD +'&nextID='+nextid;
        $("#Result").html( "" );
        $.ajax({
          type: "POST",
          url: "postData.php",
          data: dataString,
          cache: false,
          success: function(html) { $("#Result").html( html ); }
        });
      });
    });

How do you get the row ID into the newly added row>

This question has an accepted answers - jump to answer

Answers

  • allanallan Posts: 61,744Questions: 1Answers: 10,111 Site admin
    Answer ✓

    Probably the easiest way for an array sourced table is to do:

    t.row.add( [ ... ] ).node().id = 'myId';
    t.draw( false );
    

    This works because row.add() will return an API instance the same as if you had selected the row with row().

    Allan

  • koniahinkoniahin Posts: 186Questions: 39Answers: 7

    Perfect. I updated my code to the following which works splendidly:

    t.row.add( [
      '<input type="text" id="'+nextid+'" class="saveData" name="name" value="<?php echo $name; ?>">',
      '<input type="text" id="'+nextid+'" class="saveData" name="position" value="<?php echo $position; ?>">',
      '<input type="text" id="'+nextid+'" class="saveData" name="salary" value="<?php echo $salary; ?>">',
    ] ).node().id = 'nextid';
    t.draw( false );
    

    Data is now saving in the DB.

This discussion has been closed.