1

I keep getting undefined for quarterStr? I am trying to access it in the getNexthreeMonths function. So a month is chosen from a drop down menu and then I want to access the result in the getNexthreeMonths:

getNextThreeMonths: function() {
  $("#date").on('change', function (e){
    var currentMonth = $(this).find('option:selected').attr('id');
    var currentMonth = parseInt(currentMonth);
    var qNum = Math.floor(currentMonth / 3);
    var qArr = ["Jan","Apr","Jul","Oct"];
    var quarterStr = qArr[ (qNum+1) % 4 ] + "," + qArr[ (qNum+2) % 4 ] + "," + qArr[ (qNum+3)%4 ];

  });
  console.log(quarterStr);
}
Lee
  • 2,610
  • 5
  • 29
  • 36
Whymess
  • 697
  • 3
  • 8
  • 20
  • try moving console.log(quarterStr) above }); in your code. it looks like it is outside the anonymous function you defined. – Lukasz P. Oct 07 '15 at 16:50
  • I want to access the quarterStr in the getNextThreeMonths: function, though.Not sure i understand – Whymess Oct 07 '15 at 17:14
  • javascript scope: http://stackoverflow.com/questions/500431/what-is-the-scope-of-variables-in-javascript – Lee Oct 07 '15 at 17:26
  • 2
    The issue is that the scope if `quarterStr` is the callback function, not of `getNextThreeMonths`. To access the variable outside of the callback, you need to have declared it outside of the callback. – Lee Oct 07 '15 at 17:28
  • @Lee you need to post that as an answer and claim your reputation points… before I do it! ;) – gfullam Oct 07 '15 at 19:19

1 Answers1

3

There are two reasons for this.

First, the var in var quarterStr = means the variable is locally scoped to the anonymous function you pass as an argument to on() and can't be accessed outside that function.

Second, the value isn't assigned to quarterStr until the change event on the date element fires and that function is run. You're trying to read the value just after you assign the event handler. There is no way that it will have changed by then, so it will always be undefined.

You need to rethink your logic. You can't use JavaScript to time travel and figure out what the user might do at some point in the future.

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335