0

I'm making a custom calendar. I'm working on the position of the calendar days. I'm working on a function that needs to find the first time a condition is true.

Looking at my code below, I need to console.log("test") only the first time var J has a greater value than var currentDate.

Here is my code: http://jsfiddle.net/c33Xj/

$("#Cal tbody tr:first-child td").each(function(){
     var currentDate = (new Date).getDate();
     var h = $(this).text();
     if (h == weekDays[currentDay]) {
         var j = $(this).index();
         console.log(j);
     }
});
5
  • And what is j ? I mean what $(this).index() exactly is? Day of month? 0 = first day? Or 1 = first day? or what? Commented Jul 14, 2014 at 14:40
  • My calendar is a single row. J is each time the week day(eg. Mon) appears. Commented Jul 14, 2014 at 14:43
  • So by finding the first time J is greater than current date, I know what calendar day to mark as today. I can't have Jul. 23rd, fall on the first monday of my calendar. Commented Jul 14, 2014 at 14:44
  • You need to give us a html or at least function creating calendar table. Commented Jul 14, 2014 at 14:46
  • jsfiddle.net/c33Xj Commented Jul 14, 2014 at 14:47

4 Answers 4

2
return false;

will cancel the rest of the iterations.

See http://api.jquery.com/jquery.each/ (last paragraph right above Examples section.)

Sign up to request clarification or add additional context in comments.

1 Comment

wow....sometimes excess knowledge fails to find simplest solutions...perfect : +1!!
2

I would do

var e = $("#Cal tbody tr:first-child td").filter(function() { 
    return $(this).text() === weekDays[currentDay] 
}).first()

Then do whatever you want with e variable.

Comments

-1

Use a global (common) flag to all the elements and change its state the first time you call Console.log, so following times check this condition:

var logged = false;
$("#Cal tbody tr:first-child td").each(function(){
     var currentDate = (new Date).getDate();
     var h = $(this).text();
     if (h == weekDays[currentDay]) {
     var j = $(this).index();
     if(loged==false)
     {
          console.log(j);
          logged = true;
    }
 }
});

logged = false; //Restart for the next time;

Comments

-2

For identifying which day is the current day, I would use the modulus operator (%). While a division (30 / 30) leads to the result (zero), modulus means the rest. So 30 % 30 is 0, 30 % 20 is 10 (20 fits 30 one time with 10 rest) etc.

j % currentDate is zero if j is today:

if(j % currentDate == 0) {
    console.log("test");
}

1 Comment

bad idea... how about 28/31 days months?

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.