Use If Statement to change default length of table
Use If Statement to change default length of table
Hello!
I have an odd question that I'm hoping I can get some help with. My default table length is 10 rows, which is fine for most cases. However, it seems a little silly to show 10 rows if there only are, say, 11 rows in the table. Ideally, I'd like to make this setting conditional - if the number of rows is less than 15, set the length to 25. However, I can't seem to get it working. I'm using JQuery, and I'm a novice with it. Here's what I thought might work. This function is outside my initialization script.
var table = $('.TableStyle-SmartTable').DataTable();
table.each(function (value, index){
if (table.rows.count() < 15) {
table.page.len(25).draw();
}
});
My initialization script is pretty long because I've done a lot of customization, so I'd prefer not to create two separate scripts to support this use case. There are also cases where I have multiple tables on a page, so whatever solution I come up with would need to accommodate that.
Thank you in advance! I might ask some silly questions, so please be patient with me.
This question has an accepted answers - jump to answer
Answers
You are missing the
()
for therows()
API, Likely you will see an error in the browser's console for this statement.You will want to use either
initComplete
orready()
to execute the check to make sure Datatables has all the rows, especially if you are usingajax
.You can define
initComplete
using config defaults which will apply to all Datatables on the page. However if you haveinitComplete
defined in the individual Datatables configs they will take precedence.You can use
tables()
along withready()
to apply the check against all the Datatables. Here is an example usingready()
for multiple Datatables:https://live.datatables.net/socirone/34/edit
You will need to adjust the if statement to meet your requirements.
Kevin
If you choose the
ready()
solution then please monitor this thread for a change in using the API instance in the function.Kevin
Thank you @kthorngren! Your answer was very helpful. I really appreciate you taking the time to help me with this! Here was my solution, I added it to my configuration options, as you suggested.