Link to home
Start Free TrialLog in
Avatar of damoncf1234
damoncf1234

asked on

Add the first 10 rows in an HTML table to the same numbered class (increment class by 1 for the next 10 rows, etc.)

Hello,

I'm trying to add the first 10 rows in an HTML table to the same numbered class (and increment the class by 1 for rows 11-20, and again through all the rows of the table).  

"Scott Fell" provided a solution for a related question I asked last week.  
https://www.experts-exchange.com/questions/28653105/Importing-data-from-Excel-into-HTML-table-for-meeting-room-display.html

I found an example that adds class 1-6 to every row, then restarts after every 6 rows -- but I'm trying to add the same class to the first 10 rows, then add the next 10 to "class 2", the next 10 to class 3, etc...  
var i = 0;

$('ul').find('li').each(function(){

if(i<6){

i++;

}

else{

i = 1;

}

$(this).addClass('class-' + i);

});

Open in new window


I'm trying to display only 10 rows of a table at a time on an HTML page -- Scott Fell recommended the 'class' idea in his previous post - but I can't figure out how to assign 10 rows at a time to the same class.  Thank you.

-Chris
Avatar of Rainer Jeschor
Rainer Jeschor
Flag of Germany image

Hi,
to select n rows in a table you should be able to use the following:
$("#tableid").find("tr").slice(0,10).each(...

Open in new window


For 11 to 20 use slice(10,20) ...

HTH
Rainer
And one additional hint:
there is a really good jQuery plugin called datatables.net which has the paging feature, search, sorting ...
Can be found here:
http://www.datatables.net

Just my 2ct
Rainer
Avatar of damoncf1234
damoncf1234

ASKER

Rainer,

Thanks for your responses.  So we have a table that usually has ~10-20 rows that we display outside a conference room each day.  The issue is, if we have more than 10 entries, we want the screen to display the first 10 rows, pause for 10 seconds, and then display the next 10 rows, pause for 10 seconds, then loop back to the first 10 rows (and so on)...  

We'd also like rows to be 'skipped'/not displayed once their end time is earlier than the current time (there are three columns - meeting name, start, and end time).  Would this be possible with the solution above?

Thank you,
Chris
Probably then a custom solution might be better.
I will try to prototype a sample.
Excellent, thank you.
Rainer,

Hello.  Is there a way to assign the first 10 rows of a table to the same 'numbered class,' and the next 10 to another class?  Scott Fell provided pieces of a solution that should work if I could just figure out how to assign the first 10 rows to the 'same' class.

I found the code above that will assign rows to sequential class numbers -- 1, 2, 3, 4, 5, 6 -- etc...  I'm trying to assign 10 rows to the same class -- 1, 1, 1, 1, 1, 1, 1, 1, 1, 1 -- then increment to class 2 for the next 10 rows...  

Is it possible to modify this code to do this?  

var i = 0;

$('ul').find('li').each(function(){

if(i<6){

i++;

}

else{

i = 1;

}

$(this).addClass('class-' + i);

});

Open in new window


There are not always the same number of rows in the table -- sometimes there are 4 rows, other days there are 10, others there are 15 rows...  

Thanks again,
Chris
Hi Chris,

here is a prototype I built in jsbin:
Code:
http://jsbin.com/tecule/1/edit?html,js

Live preview:
http://jsbin.com/tecule/1

Instead of assigning classes, I used an interval and a base array of meetings as well as a calculated temporary array for the meetings to display and rebuild the table rows every ten seconds - including the logic to not use any meeting where end datetime is lower then now.

I used one additional helper plugin called moment.js so that the initial meeting array is created dynamically (adding / substracting minutes and seconds) - so that the sample works at any time without having to adjust the end dates.
The initial array could also be generated via a web service / Ajax / Get call.

HTH
Rainer
Hi Chris,

and here a sample to set only different classes:
http://jsfiddle.net/EE_RainerJ/xgutL216/

jQuery code:
$(document).ready(function() {
    var linesPerPage = 4;
    var rowCount = $("tr",$("#meetingtable > tbody")).length;
    var noOfPages = Math.floor(rowCount/linesPerPage) + 1;

    for (i=0;i<noOfPages;i++) {
        $("tr",$("#meetingtable > tbody")).slice(i*linesPerPage,(i*linesPerPage)+linesPerPage).each(function() {
            $(this).addClass('row-' + (i+1));
        });
    }
});

Open in new window


Important: the selector expects a tbody. If you have "just" a table you might have to change the logic a bit, because the header row will also be a row.
HTH
Rainer
Rainer,

Excellent - thank you.  Currently, the table rows come from a CSV file that I have on the c: drive of the system (it's basically a system we use to display a list of meetings, with start and end times).  

Your first solution looks great -- I noticed that the rows are manually typed into the code -- how would I change that so that the rows would be pulled from a CSV file on the c: drive?  Thank you.  

-Chris
Rainer,

Hello again.  I tried applying the solution you provided on 4/23 using a set of arrays instead of classes -- it handles both the 10-row issue, along with the 'removing old entries' issue.  When I tried including it in my html page, it didn't work - probably because the data in my rows is pulled from a CSV file stored locally on each workstation.  

Below is a script that is in the head of the page I'm using:

<script src="file://c:/test/IDS/jquery-1.11.1.min.js"></script>

  <script>
  $(function(){ // Call when html is done loading
$.ajax({ //Your url will be filename.csv or folder/filename.csv
  method: "get",
  url: "meetingtable.csv"

})
  .done(function( data ) {
    var lines = data.split("\n"); // split on line break
    $.each(lines,function(i){     // loop through each line
       var rowdata = lines[i];    // assign the row a variable
                                 // data looks like rowdata = "1,2,3"
       $("table#meetingtable tbody").append("<tr><td>"+rowdata.replace(/,/g,"</td><td>")+"</td></tr>"); 
      // replace all commas with ending and starting td tags then append row to table
    });
  });
});  
  </script>

Open in new window


I noticed in your first solution, the meeting/row data is actually typed into the script itself...  How could your script be modified to pull the the data for each row from the CSV file that my data is stored in on the c: drive of each workstation?  I think once this is figured out, my HTML page will be complete.  

Thank you again,

Chris
Rainer,

In other words, instead of having the meeting name/start/end times written in the code like your example:

var listOfMeetings = [
  {
    Name: "Event One",
    StartDT: moment().subtract(10, 'm'),
    EndDT: moment().subtract(9, 'm')
  },
  {
    Name: "Event Two",
    StartDT: moment().subtract(8, 'm'),
    EndDT: moment().subtract(7, 'm')
  },
  {
    Name: "Event Three",
    StartDT: moment().subtract(6, 'm'),
    EndDT: moment().subtract(5, 'm')
  },
];

Open in new window


Have the row data (meeting name/start/end times) get pulled from a CSV file on the c: drive.  

How could this be done?  Can your solution pull from the CSV file using the script I posted in the previous comment?  

Thank you again.  

-Chris
Hi Chris,
the following should work BUT depends on your browser (e.g. it does not work with Chrome as the Ajax call is NOT supported on local file system - you would need a "real" web server to serve the CSV (can also be a really tiny one installed locally)):
<!DOCTYPE html>
<html>
<head>
<meta name="description" content="Dynamic table paging with interval">
<script src="jquery.min.js"></script>
  <script src="moment.js"></script>
  <title>EE - Dynamic Table</title>

<style id="jsbin-css">
table
td {border: 1px solid black}
</style>
</head>
<body>
  <table id="meetingtable" width="100%">
    <thead>
        <tr>
            <td>Meeting</td>
            <td>Starts at</td>
            <td>Ends at</td>
        </tr>
    </thead>
    <tfoot>
        <tr>
            <td>Meeting</td>
            <td>Starts at</td>
            <td>Ends at</td>
        </tr>
    </tfoot>
    <tbody>
    </tbody>
</table>
  
<script>
var listOfMeetings = [];

var pagePageSize = 1;
var currentIndex = 0;
var tableTimer = null;
    
$(document).ready(function() {
  $.ajax({ //Your url will be filename.csv or folder/filename.csv
	method: "get",
	url: "meetingtable.csv",
	crossDomain: true
	})
	.done(function( data ) {
		var lines = data.split("\n"); // split on line break
		$.each(lines,function(i){     // loop through each line
			var rowdata = lines[i].split(",");    // assign the row a variable and build array
			listOfMeetings.push({
				Name: rowdata[0],
				StartDT: moment(rowdata[1]),
				EndDT: moment(rowdata[2])
			});
		});
		RebuildTable();
		tableTimer = setInterval(function () {RebuildTable();}, 10000);
	});
});

function RebuildTable() {
    // Hide the table
    $("#meetingtable").slideToggle("slow");
    
    // Container getting remaining meetings
    var currentListOfMeetings = [];
    
    // Verify each entry
    $.each(listOfMeetings,function(index, element) {
      if (moment(element.EndDT) >= moment()) {
        currentListOfMeetings.push(element);
      }
    });
  
    // Calculate max paging number
    pageSize = Math.floor(currentListOfMeetings.length/10) + 1;
  
    if(pageSize == 1 || pageSize <= (currentIndex + 1)) {
      currentIndex = 0;
    } else {
        currentIndex += 1;
    }
    
    // Reset tbody content
    $("tbody",$("#meetingtable")).empty();
  
    // Rebuild rows
    $.each(currentListOfMeetings.slice(currentIndex*10,(currentIndex*10)+10),function(index, element) {
      $("tbody",$("#meetingtable")).append("<tr><td>"+element.Name+"</td><td>"+moment(element.StartDT).format('YYYY-MM-DD hh:mm')+"</td><td>"+moment(element.EndDT).format('YYYY-MM-DD hh:mm')+"</td></tr>");  
  });
    // Show the table
    $("#meetingtable").slideToggle("slow");
}
</script>
</body>
</html>

Open in new window


You would just need to download the jQuery and the moment.js library and store it locally.
Which browser are you using (as well as client OS)?
HTH
Rainer
Rainer.

That looks great - we're using IE, and win7.  We also have Firefox installed, but we'll use IE to run this page.  

I noticed in one of the last lines of your solution that the start and end fields are in the YYYY-MM-DD hh:mm:ss format - if we just want to display the hh:mm portion, I can just modify that line, correct?  (And it will still remove the rows with end times that are earlier than the current time?)  I'll test it out today.  Thank you again,

Chris
Hi Chris,
For the display you should simply use the moment.js functionality for the output, but internally storing the complete date.
I will have a look on it tonight.
HTH
Rainer
Rainer,

Hello again.  I tried to test updated code just the way it is above (using the CSV file), and it wouldn't display any of the rows from the CSV file (just the header/footer from the actual HTML code).  

I also tried to incorporate it into the page that I have running, and it doesn't seem to display the data from the CSV file.  

My current/working page pulling from the CSV file on the c: drive:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Display Date and Time in Javascript</title>
        <script type="text/javascript" src="JS\date_time.js"></script>

<script language="JavaScript1.1">
<!--

/*
JavaScript Image slideshow:
By JavaScript Kit (www.javascriptkit.com)
Over 200+ free JavaScript here!
*/

var slideimages=new Array()
var slidelinks=new Array()
function slideshowimages(){
for (i=0;i<slideshowimages.arguments.length;i++){
slideimages[i]=new Image()
slideimages[i].src=slideshowimages.arguments[i]
}
}

function slideshowlinks(){
for (i=0;i<slideshowlinks.arguments.length;i++)
slidelinks[i]=slideshowlinks.arguments[i]
}

function gotoshow(){
if (!window.winslide||winslide.closed)
winslide=window.open(slidelinks[whichlink])
else
winslide.location=slidelinks[whichlink]
winslide.focus()
}

//-->
</script>

<script src="file://c:/test/IDS/jquery-1.11.1.min.js"></script>
  <script>
  $(function(){ // Call when html is done loading
$.ajax({ //Your url will be filename.csv or folder/filename.csv
  method: "get",
  url: "schedule.csv"

})
  .done(function( data ) {
    var lines = data.split("\n"); // split on line break
    $.each(lines,function(i){     // loop through each line
       var rowdata = lines[i];    // assign the row a variable
                                 // data looks like rowdata = "1,2,3"
       $("table#schedule tbody").append("<tr><td>"+rowdata.replace(/,/g,"</td><td>")+"</td></tr>"); 
      // replace all commas with ending and starting td tags then append row to table
    });
  });
  
});  
  </script>

<style>
table#schedule td {
    width: 100%;
    text-align:left;    
    font-family:verdana;
    font-size:18px;
    font-weight:bold;
    padding: 8px;
} table#schedule th {
    width: 100%;    
    text-align:left;
    font-family:verdana;
    font-size:18px;
    font-weight:bold;
    text-decoration:underline;
    padding: 8px;
}
#PHOTO{
    width:200px;
    height:200px;
}
#PHOTO img{
    width:auto;
    height:400px;
    display:block;
}
</style>

    </head>

    <body bgcolor="#000066" text="#FFFFFF">

<TABLE ID="IDS" align="center" width="100%">

<TR><TD height="33%">

<TABLE ID="Header" align="center" width="80%"><TR><TD>

	<H1 style="font-size:110%;text-align:center;font-family:verdana">
            <span id="date_time"></span>
            <script type="text/javascript">window.onload = date_time('date_time');</script>
	</H1>
	
	<P style="font-size:240%;text-align:center;font-family:verdana;font-weight:bold">
	Today's schedule for
	</P>
	<P style="font-size:220%;text-align:center;font-family:verdana;font-weight:bold">
	Conferencd Room B
	</P>
	<P></P>

</TD></TR></TABLE>

</TD></TR>

<TR><TD>

<TABLE ID="PHOTO" align="center" width="80%"><TR><TD>

<P style="text-align:center"> <img src="1.jpg" name="slide" border=0> </P>
<script>
<!--

//configure the paths of the images, plus corresponding target links
slideshowimages("1.jpg","2.jpg","3.jpg","4.jpg","5.jpg")
slideshowlinks("images\1.jpg","images\2.jpg","images\3.jpg","images\4.jpg","images\5.jpg")

//configure the speed of the slideshow, in miliseconds
var slideshowspeed=10000

var whichlink=0
var whichimage=0
function slideit(){
if (!document.images)
return
document.images.slide.src=slideimages[whichimage].src
whichlink=whichimage
if (whichimage<slideimages.length-1)
whichimage++
else
whichimage=0
setTimeout("slideit()",slideshowspeed)
}
slideit()

//-->
</script>

</TD></TR></TABLE>

</TD></TR>

<TR><TD height="33%">

  <table id="schedule" align="center" width="100%">
    <thead align="left"><tr><th>Meeting Name</th><th>Start</th><th>End</th></tr></thead>
  <tbody align="left"></tbody>
  </table>

</TD></TR>
</TABLE>

    </body>
</html>

Open in new window


How I tried to apply the latest solution you provided to use the CSV file with the 10-row page and removal of old meetings feature with moment.js:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
    <head>
        <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
        <title>Display Date and Time in Javascript</title>
        <script type="text/javascript" src="JS\date_time.js"></script>

<script language="JavaScript1.1">
<!--

/*
JavaScript Image slideshow:
By JavaScript Kit (www.javascriptkit.com)
Over 200+ free JavaScript here!
*/

var slideimages=new Array()
var slidelinks=new Array()
function slideshowimages(){
for (i=0;i<slideshowimages.arguments.length;i++){
slideimages[i]=new Image()
slideimages[i].src=slideshowimages.arguments[i]
}
}

function slideshowlinks(){
for (i=0;i<slideshowlinks.arguments.length;i++)
slidelinks[i]=slideshowlinks.arguments[i]
}

function gotoshow(){
if (!window.winslide||winslide.closed)
winslide=window.open(slidelinks[whichlink])
else
winslide.location=slidelinks[whichlink]
winslide.focus()
}

//-->
</script>

<script src="file://c:/test/IDS/jquery-1.11.1.min.js"></script>
  <script src="file://c:/test/IDS/moment.js"></script>

<style>
table#meetingtable td {
    width: 100%;
    text-align:left;    
    font-family:verdana;
    font-size:18px;
    font-weight:bold;
    padding: 8px;
} table#meetingtable th {
    width: 100%;    
    text-align:left;
    font-family:verdana;
    font-size:18px;
    font-weight:bold;
    text-decoration:underline;
    padding: 8px;
}
#PHOTO{
    width:200px;
    height:200px;
}
#PHOTO img{
    width:auto;
    height:400px;
    display:block;
}
</style>

    </head>

    <body bgcolor="#000066" text="#FFFFFF">

<TABLE ID="IDS" align="center" width="100%">

<TR><TD height="33%">

<TABLE ID="Header" align="center" width="80%"><TR><TD>

	<H1 style="font-size:110%;text-align:center;font-family:verdana">
            <span id="date_time"></span>
            <script type="text/javascript">window.onload = date_time('date_time');</script>
	</H1>
	
	<P style="font-size:240%;text-align:center;font-family:verdana;font-weight:bold">
	Today's schedule for
	</P>
	<P style="font-size:220%;text-align:center;font-family:verdana;font-weight:bold">
	Conference Room B
	</P>
	<P></P>

</TD></TR></TABLE>

</TD></TR>

<TR><TD>

<TABLE ID="PHOTO" align="center" width="80%"><TR><TD>

<P style="text-align:center"> <img src="1.jpg" name="slide" border=0> </P>
<script>
<!--

//configure the paths of the images, plus corresponding target links
slideshowimages("1.jpg","2.jpg","3.jpg","4.jpg","5.jpg")
slideshowlinks("images\1.jpg","images\2.jpg","images\3.jpg","images\4.jpg","images\5.jpg")

//configure the speed of the slideshow, in miliseconds
var slideshowspeed=10000

var whichlink=0
var whichimage=0
function slideit(){
if (!document.images)
return
document.images.slide.src=slideimages[whichimage].src
whichlink=whichimage
if (whichimage<slideimages.length-1)
whichimage++
else
whichimage=0
setTimeout("slideit()",slideshowspeed)
}
slideit()

//-->
</script>

</TD></TR></TABLE>

</TD></TR>

<TR><TD height="33%">

  <table id="meetingtable" align="center" width="100%">
    <thead align="left"><tr><th>Meeting Name</th><th>Start</th><th>End</th></tr></thead>
  <tbody align="left"></tbody>
  </table>

</TD></TR>
</TABLE>

<script>
var listOfMeetings = [];

var pagePageSize = 1;
var currentIndex = 0;
var tableTimer = null;
    
$(document).ready(function() {
  $.ajax({ //Your url will be filename.csv or folder/filename.csv
	method: "get",
	url: "meetingtable.csv",
	crossDomain: true
	})
	.done(function( data ) {
		var lines = data.split("\n"); // split on line break
		$.each(lines,function(i){     // loop through each line
			var rowdata = lines[i].split(",");    // assign the row a variable and build array
			listOfMeetings.push({
				Name: rowdata[0],
				StartDT: moment(rowdata[1]),
				EndDT: moment(rowdata[2])
			});
		});
		RebuildTable();
		tableTimer = setInterval(function () {RebuildTable();}, 10000);
	});
});

function RebuildTable() {
    // Hide the table
    $("#meetingtable").slideToggle("slow");
    
    // Container getting remaining meetings
    var currentListOfMeetings = [];
    
    // Verify each entry
    $.each(listOfMeetings,function(index, element) {
      if (moment(element.EndDT) >= moment()) {
        currentListOfMeetings.push(element);
      }
    });
  
    // Calculate max paging number
    pageSize = Math.floor(currentListOfMeetings.length/10) + 1;
  
    if(pageSize == 1 || pageSize <= (currentIndex + 1)) {
      currentIndex = 0;
    } else {
        currentIndex += 1;
    }
    
    // Reset tbody content
    $("tbody",$("#meetingtable")).empty();
  
    // Rebuild rows
    $.each(currentListOfMeetings.slice(currentIndex*10,(currentIndex*10)+10),function(index, element) {
      $("tbody",$("#meetingtable")).append("<tr><td>"+element.Name+"</td><td>"+moment(element.StartDT).format('YYYY-MM-DD hh:mm')+"</td><td>"+moment(element.EndDT).format('YYYY-MM-DD hh:mm')+"</td></tr>");  
  });
    // Show the table
    $("#meetingtable").slideToggle("slow");
}
</script>

    </body>
</html>

Open in new window


Do you see any issues with the way I applied your solution to my existing page?  Thank you again for your help.  

-Chris
Hi Chris,
at least in Chrome it is not running as Chrome detects a cross site / cross origin request and therefore the Ajax get is not running - this would require a http / https schema (and not file:).

I have currently no Win7 available - which IE version?
If this was running before it should run afterwards as well - as this part "just" relies on the jQuery version.
HTH
Rainer
Rainer,

Hello.  Right now it's IE 11.  Yeah, if I run the original version of my html page, it runs fine.  

Did I insert your solution in the right location on the page - or is it missing something?  I saved a local copy of the moment.js file to the same directory as the other files...  

Thank you,
Chris
Hi Chris,
could you perhaps attach your current working solution (or send it via EE message) - HTML, script files, CSV ? So that I have something where I can start from (getting it running and then proceeding).
Thanks.
Rainer,

Sure - attached is the working HTML page (displays rows from the CSV file) -- but doesn't include your latest solution (10-rows, removing old rows, etc.).  Also attached is the test CSV file I'm using, along with jquery-1.11.1.min, date_time.js, and moment.js.

Trying to figure out how to add your solution posted on 2015-04-28, but I can't get that to work properly even by itself.  

Thank  you again,
Chris
MeetingRoomDisplay.html
meetingtable.csv
date-time.js
jquery-1.11.1.min.js
moment.js
Rainer,

Hello.  I attached the working version of the page, along with the scripts and a csv file; any luck incorporating the solution you posted?  

Thank you again,

Chris
ASKER CERTIFIED SOLUTION
Avatar of Rainer Jeschor
Rainer Jeschor
Flag of Germany image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Rainer,

Hello - this looks great; I'll test it and let you know the results - thank you for your help again!  

Say hello and thank you to your twins and your wife - sorry for taking time from your weekend.  

Thank you,
Chris
Rainer,

Hello again - I tested your latest solution and it works great!  I modified the time format that is displayed from moment.js to show a 12-hour time with am/pm ('h:mm a').  Excellent solution.  Thank you for your numerous posts to get this solution.  

-Chris
Excellent solution, spread over several posts.  Thank you.