0

I'm currently using jQuery datatables to make the table I am displaying. Currently I have it set up so when I select a row in the table, the text in that row appears in a textbox in another panel. I can then type in something else and press "Save" and it changes the text in that row. My current issue is when I add a new row via a button, I cant edit the text in the new row, I can select it however... Example: I have 3 rows, I select Test1 and I can successfully change the text. Then I click Add Row and then I select the new row and attempt to change the text in that row, it changes the previously selected row's text (a row that was in the table upon load). How can I fix this issue? I've looked into cell.data, cell.edit but that's for the Editor which I'm not currently using for various reasons.

Table:

<div class="panel-body">
                <table id="data-table" class="table table-striped table-bordered nowrap" width="100%">
                    <thead>
                        <tr>
                            <th>Name</th>
                        </tr>
                    </thead>
                    <tbody>
                        <tr class="odd">
                            <td>All</td>
                        </tr>
                        <tr class="even">
                            <td>Test1</td>
                        </tr>
                        <tr class="odd">
                            <td>Test2</td>
                        </tr>
                    </tbody>
                </table>
                <div class="col-md-8 col-md-offset-1">
                    <button type="submit" class="btn btn-sm btn-primary m-r-5" id="addbtn" >New Group</button> 
                </div>
            </div>
//Text box
<div class="form-group">
                <label class="col-md-4 control-label">Group Name:</label>
                    <div class="col-md-8">
                        <input type="text" id="groupname" class="form-control" value="Name"/>
                    </div>
            </div>

Code for making the selected row's text appear in textbox:

(function () {

      var table = document.querySelector('#data-table');
      var textbox = document.querySelector('#groupname');

      table.addEventListener('click', onTableClick);

      function onTableClick (e) {
        var tr = e.target.parentElement;

        var data = [];
        for (var td of tr.children) {
          data.push(td.innerHTML);
        }
        textbox.value = data[0];
      }
    })();

Changing the selected row's text:

    var row = null;

    $("#data-table tr td").click(function() {
      $("#groupname").val($(this).text());
      row = $(this);


        $("#saverow").click(function() {
          if (row != null) {
            row.text($("#groupname").val());
          }
        });
    });

Add row:

$("#addbtn").click( function() {
    var t = $('#data-table').DataTable();

$('#data-table').dataTable();
    t.row.add( [
        "New Group"
     ] ).draw( false );
});
J. Doe43
  • 207
  • 2
  • 6
  • 20
  • I think your problem is duplicate ids. You may only have one instance of an id in an html document. The reason it's editing the previous row's text is because you're selecting by id for almost everything, and it's only going to find the first result on the page. – ebraley Jul 18 '17 at 19:27
  • The selected tag is added into the class tag. I can successfully change the text for all 3 rows I have coded into the html, but once I add a new row, I cant change that row's text. I can still change all other rows text though. – J. Doe43 Jul 18 '17 at 19:42

2 Answers2

1

Why do you have these two conflicting statements on table click?

  1. Set groupname input to first column in row user just clicked

    function onTableClick (e) {
        ...
        textbox.value = data[0];
        ...
    }
    

    Here, textbox.value = data[0] seems to be setting the '#groupname' input field's text value to the first column of whatever row just got clicked.

  2. Set input to text of cell we clicked on

    $("#data-table tr td").click(function() {
        ...
        row.text($("#groupname").val());
        ...
    });
    

Here, row.text($("#groupname").val()); seems to be setting the '#groupname' input field's text value to the text of the exact column we clicked on.

By the way, row here is a misleading variable name because the actual element $(this) is referring to is any td which is a child of a tr which is a child of '#data-table'. So really $(this) is a column or table cell; calling it row is confusing.

anandsun
  • 186
  • 6
  • Thanks for your comment, I'm still fairly new to coding and missed the conflict here. I got rid of the "function onTableClick (e) { ... textbox.value = data[0]; ... }" code. Although I am still stuck on how I can accomplish my original goal. – J. Doe43 Jul 18 '17 at 19:53
  • Does DataTables' `row.add()` actually add a `td`? See [https://datatables.net/reference/api/row.add()](https://datatables.net/reference/api/row.add()). It looks like it might just add a `tr`. In that case `$("#data-table tr td").click(function() .. )` won't run for the newly added rows, right? – anandsun Jul 19 '17 at 14:18
0

As stated here, by andreister, when we use .click, a separate handler gets created for every single element that matches the selector. That means

  1. many matching elements would create many identical handlers and thus increase memory footprint
  2. dynamically added items won't have the handler - ie, in the above html the newly added "Alert!" buttons won't work unless you rebind the handler.

But when we use .on, there's a single handler for all elements that match your selector, including the ones created dynamically.

So I changed

$("#data-table tr td").click(function() {

to

$("#data-table").on('click', 'td', function() {

to fix my issue.

J. Doe43
  • 207
  • 2
  • 6
  • 20
  • Please have a look at [how to answer](https://stackoverflow.com/help/how-to-answer) and update your answer to provide more detail. Specifically, it would be helpful if you explained how this solves the problem. - [From Review](https://stackoverflow.com/review/low-quality-posts/16753077) – Ortund Jul 19 '17 at 07:23