Whymess
Whymess

Reputation: 717

Variable scope outside of JQuery Event

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);
}

Upvotes: 1

Views: 428

Answers (1)

Quentin
Quentin

Reputation: 943569

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.

Upvotes: 3

Related Questions