0

I have a monthly calendar which displays days with events happening in this day. This is how generated HTML looks like:

<table class="event-cal">
  <tbody>
     <tr class="eventcont event-93">
        <td class="eventtime">19:00</td>
        <td><a class="calendar-title" href="#>Event title</a><br></td></tr>
     <tr class="eventcont event-237">
        <td class="eventtime">13:00</td>
        <td><a class="calendar-title" href="#">Event 2 title</a><br></td></tr>
  </tbody>
</table>

What I want to do is to order tr.eventcont elements based on contents of .eventtime child element. Ordering has to be done within .event-cal element which contains these particular .eventcont elements because I will have several .event-cal elements in the page.

Here is the code I have so far but what it does it takes all tr.eventcont elements from page and pastes them all into each .event-cal table.

$( document ).ready(function() {
var list = $(".event-cal").find(".eventcont");
        list.sort(sortDesc);
        $(".event-cal").html("");
        $(".event-cal").append(list);
    });
    function sortDesc(a, b){
        var test1 = jQuery(a);
        var test2 = jQuery(b);
        return test1.find(".eventtime").text() > test2.find(".eventtime").text();
}
2
  • You're appending to $(".event-cal"), which is every table that has the class 'event-cal'. If you want it to only append it to the table you're finding them in, you need to specify this function for each table appart, like in the answers. Commented Feb 16, 2016 at 14:22
  • It should be noted that the sort function seems flawed, for instance "10:00" < "2:00" etc. Commented Feb 16, 2016 at 14:26

2 Answers 2

3

You need to run your function for each table using jquery.fn.each

$('.event-cal').each(function() {
   var table = $(this),
      list = table.find('.eventcont').sort(sortDesc);

   table.empty().append(list);      
});
Sign up to request clarification or add additional context in comments.

3 Comments

@Yury, can you please explain this function? I'm testing it, but I get sortDesc is not defined
@Vixed sortDesc is the function that Daria created on the question.
ups, sorry! I was working on my answer that's why I haven't seen it, ahahah I didn't used ;)
0

Check this fiddle

$(".event-cal").each(function(){
  var events=$('tr',this);
  events.sort(function (a, b) {
      a = parseInt($('.eventtime',a).text().replace(':',''));
      b = parseInt($('.eventtime',b).text().replace(':',''));
      if(a > b) {
          return 1;
      } else if(a < b) {
          return -1;
      } else {
          return 0;
      }
  });
  $(this).html(events);
});

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.