2

I have a table set out like:

<table id="myTable">
  <thead>
    <tr>
      <td><input type="checkbox" id="selectall" /></td>
      <td>Column 1</td>
      <td>Column 2</td>
      <td>Column 3</td>
      <td>Column 4</td>
      <td>Column 5</td>
    </tr>
  </thead>
  <tbody>
  </tbody>
</table>

Then, the javascript:

var myTable = jQuery('#myTable').dataTable({
    /* options */
});

// Ajax request to populate:
jQuery.get('script.php', function(data){
    eval("rows="+data);
    for(var i=0;i<rows.length;i++){
        myTable.fnAddData([
          "<input type=\"checkbox\" id=\""+rows[i].uniqueID+"\" />",
          rows[i].col1Txt,
          rows[i].col2Txt,
          rows[i].col3Txt,
          rows[i].col4Txt,
          rows[i].col5Txt ]);
    }
});

Now, I am having trouble with updating the table based on which checkboxes are selected:

I am trying to update the 5th cell in each row that is checked. I am using a combination of fnUpdate and fnGetPosition (http://www.datatables.net/api).

fnGetPosition expects the td or tr element, so I thought I'd just grab the parent td of the checkboxes:

var checkBoxes = jQuery('td > input:checked', myTable);
for(var i=0;i<checkBoxes.length;i++){
    var parentTD = jQuery('#'+checkBoxes[i].id).parent(); //seems wrong?
    var pos = myTable.fnGetPosition(parentTD);
    //alert(pos[0]);
    myTable.fnUpdate('Updated text', pos[0], 5);
}

But I must be doing parentTD wrong since pos never seems to hold a value.

Any ideas?

1 Answer 1

7

you can use the each function to iterate over a jQuery object, its easier than using the for loop.

Also, I think that you can optomise your selector to get you the td elements instead of geting the checked inputs.

It will be a lot more performant as it should remove 2 selectors in every operation. I haven't tried it but something like this should work

var checkBoxes = jQuery('td:has(input:checked):not(#selectall)', myTable);
checkboxes.each(function(){
    var pos = myTable.fnGetPosition($(this)); // Im not familiar with the plugin so the extra $() might be overkill
    alert(pos) // maybe run this alert again, check if you get back an object/value? use firebug to debug and see its value?
    myTable.fnUpdate('Updated text', pos[0], 5);
});
Sign up to request clarification or add additional context in comments.

2 Comments

Nice one, that worked. I was aware of each(), I just couldn't gather my limited jQuery knowledge to grab all those tds. Thanks very much.
How is this now with the newer API?

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.