Spencer
Spencer

Reputation: 642

jQuery iterate through table cells and add hour from loop

I have the following code which loops through hours 0600-2300. Basically, I want to take the hours and add them to a table cell attribute. There are multiple td.daterow rows, each with columns for hours 0600-2300.

for (var h = 6; h < 24; h++)
{
  $( "td.daterow" ).each(function() {
     $(this).attr("data-hour", h);
  });
}

But this code doesn't loop through the hours like I'd like. Instead of having cells with attributes 0600-2300, it just adds "23" to each data-hour. How can I loop through the hours and add them accordingly?

============================

Also, I'm not sure how complicated this would be to add. If each cell is split into two cells to accommodate for the 30 minute interval (so 36 columns total). Would it possible to include whole hours as well as their respected 30 minute interval with the loop (if that makes sense)?

Upvotes: 1

Views: 476

Answers (4)

elzaer
elzaer

Reputation: 729

var h = 6;
$( "td.daterow" ).each(function() {
  if(h<24 && h>=6) {
    $(this).attr("data-hour", h + "00");
    h++;
  }
});

Upvotes: -1

mvw
mvw

Reputation: 5105

You perform two nested loops, the for and the each() loop with fixed h.

This might work (sorry I am on iPad now, can not test :-)

$.each($("td.daterow"), function(idx, ele) {
  var h = 6 + (idx % 18);
  ele.attr("data-hour", h);
});

Extended version:

$.each($("td.daterow"), function(idx, ele) {
  var i = idx % 36;
  if (i % 2 == 0) {
    var h = 6 + (i / 2);
    ele.attr("data-hour", h);
  } else {
    var h = 6 + ((i-1)/2);
    ele.attr( /* half hour treatment based on h */);
  }
});

Upvotes: 0

msnider
msnider

Reputation: 444

You need to walk through your loop more carefully. Each iteration you are executing $(this).attr("data-hour", h) on all of the td.daterow elements.

So in the first iteration, h=6 and you set each data-hour to 6. In the second iteration, h=7, and you now overwrite each data-hour attribute with 7. As we loop, this continues until each data-hour is 23, at which point h=24 and the loop terminates.

I'm not exactly sure what you are trying to do, but I think you want to set each data-hour to a successively higher value (or hour). You could do something like this:

var arr = $("td.daterow");
for (var h = 6; h < 24; h++) {
    $(arr[h-6]).attr("data-hour", h);
}

Upvotes: 2

Sam
Sam

Reputation: 42387

Assuming the correct amount of table cells already exist, the problem is simply that for each hour value, you are looping over each table cell and setting it. Naturally, each hour value will overwrite the previous ones.

To fix this, remove your outer loop and use the index of the td element to determine the hour.

$( "td.daterow" ).each(function(index) {
    var hour = index + 6;
     (this).attr("data-hour", hour);
  });

Upvotes: 2

Related Questions