0

Here is my code:

var pickupdate;
$(function(){
  $.datepicker.setDefaults(
    $.extend( $.datepicker.regional[ '' ] )
  );
  $( '#pickupdate' ).datepicker( {
    dateFormat: 'yy-mm-dd',
    maxDate: "+3m",
    minDate: 0,
    onSelect: function() { 
      pickupdate = $(this).datepicker( 'getDate' ); 
      alert(pickupdate)
 }
  });
});
console.log(pickupdate)

The alert (within function) works while the console.log (outside function) shows pickupdate as undefined. What am I doing wrong?

james
  • 3,989
  • 8
  • 47
  • 102

1 Answers1

1

When you do

$(function(){
    //Code here
});

You're basically binding that function to jQuery's document ready function, which is called after console.log(pickupdate) executes. The reason why it says pickupdate is undefined is because the onSelect function for the datepicker has not fired yet.

You could try encasing it in a function:

function LogValue() {
    console.log(pickupdate);
}

Then you could add that function as a click event to a button, and you'll see that when you change the datepicker value and click the button, it will log the correct value. Fiddle Here

Stryner
  • 7,288
  • 3
  • 18
  • 18