Getting values from a single column for all selected rows

Getting values from a single column for all selected rows

galcottgalcott Posts: 53Questions: 15Answers: 1

I'm trying to do something which seems like it should be simple but has taken me a long time to figure out. I'm using the Select extension and just want to get the values from the first column in all selected rows. After some searching I've come up with the following code. It works but I thought it would be possible to do this using pure DataTables code, somehow combining column and row selectors to get the values. Is there another way to do this?

var selectedRows = dtFormulas.rows('.selected').data();
values='';
$.each(selectedRows, function(index, value) {values=values + value[0] + '  ';}); // value[0] is first column
return(values);

Replies

  • allanallan Posts: 63,455Questions: 1Answers: 10,465 Site admin
    let rows = dtForumulas.rows( { selected: true } );
    return dtForumulas.cells( rows, 0 ).data();
    

    That selects the selected rows and then uses cells().data() to get the data for those rows, using the rows and column index 0 as selectors.

    Allan

  • galcottgalcott Posts: 53Questions: 15Answers: 1

    Thanks, that certainly wasn't obvious.

    I've been a bit confused about the syntax for retrieving selected rows. Are rows('.selected') and rows( { selected: true } ) equivalent? And are there other properties that can be specified in different ways.

  • allanallan Posts: 63,455Questions: 1Answers: 10,465 Site admin

    Are rows('.selected') and rows( { selected: true } ) equivalent?

    No - but close enough that most people get away with it.

    {selected: true} is the correct way to do it if you are using the Select extension, and that is what is documented.

    Generally they are the same, but consider the case when you use deferRender and then use the API to select rows which are not visible. Using a class selector (.selected) would only be able to select rows which have been created already.

    And are there other properties that can be specified in different ways.

    Probably, but I can't think of anything off the top of my head. Stick with the documentation and it should be okay. The information you might find in the forum isn't always perfect or up to date (its simply impossible for me to curate everything).

    Allan

  • t_n_tt_n_t Posts: 1Questions: 0Answers: 0

    dtForumulas.cells( rows, 0 ).data();

    This works fine when only one row is selected. But for me returns a empty array when two or more rows are selected. Maybe it is a bug.

  • kthorngrenkthorngren Posts: 21,303Questions: 26Answers: 4,947

    Maybe something like this will work:

    var rows = table.rows( { selected: true } ).indexes();
    dtForumulas.cells( rows, 0 ).data();
    

    Kevin

This discussion has been closed.