How do you know how many columns you have selected?

How do you know how many columns you have selected?

adjenksadjenks Posts: 22Questions: 6Answers: 0

When I use the following:
$('#mytable').DataTable().columns(':visible')[0].length
I can get the number of selected columns, but is that the right way to do it? Why are they stored in index zero? If I try .length on the columns() function, I always get 1, which is just the single celled array containing the actual results. Is there a .size() or a .count() or something like that? If there isn't something like that, will this short length array ever disappear? Can I trust it from version to version?

This question has an accepted answers - jump to answer

Answers

  • kthorngrenkthorngren Posts: 21,344Questions: 26Answers: 4,954
    edited August 2019 Answer ✓

    I can get the number of selected columns, but is that the right way to do it?

    When you say selected do you mean visible as opposed to using the Select extension?

    Long answer:

    I'll assume you mean visible as your example indicates. Using columns() returns an API instance as described in the API docs. in the docs it says this about the API result set:

    Result set - the data held by the API instance. DataTables API instances are "array like" in that they hold data in the same way as a plain Javascript array (and thus can be accessed using array [] notation)...

    If you console.log $('#mytable').DataTable().columns(':visible') you would see it is an API with an array of items. The first element in the array is the array of visible column indexes. Which is why you need to use [0].length to access the first API element then to get the length.

    Short answer:

    Yes, your example is one way to get the length. There is a count() API that can be used. It would look something like this: $('#mytable').DataTable().columns(':visible').count();

    If there isn't something like that, will this short length array ever disappear? Can I trust it from version to version?

    I would expect the API structure to remain the same with Datatables 1.10. This may change with Datatables 2.x - @allan can answer that.

    HTH

    Kevin

  • adjenksadjenks Posts: 22Questions: 6Answers: 0

    Thank you for your clear answer. I will avoid using the array and instead rely on the count() API method. I supposed I just looked in the wrong place when trying to find the method. Thanks again.

This discussion has been closed.