How to redirect page using targetURL with my datepicker

I am tweaking with Twisty’s script – Using Jquery UI Datepicker to redirect to URL: Change URL value based on the selected date

I am trying let user click on a date which will be redirect to a page according to the date selected. But I am getting this alert – Redirect to undefined, no matter how I tweaked the script.
Hence, I would appreciate your help. Thank you.

Pick a date:

<script>
$(function() {
  function getDayOfYear(n) {
    var s = new Date(n.getFullYear(), 0, 0);
    var d = (n - s) + ((s.getTimezoneOffset() - n.getTimezoneOffset()) * 60 * 1000);
    var oneDay = 1000 * 60 * 60 * 24;
    var day = "00" + Math.floor(d / oneDay);
    return day.substr(-3);
  }

  var targetUrl;

  $("#datepicker")
    .datepicker({
      dateFormat: 'dd-mm-yy',
      onSelect: function(dateText) {
      datePicked = $.datepicker.parseDate('dd-mm-yy', dateText);
       dayPicked = getDayOfYear(datePicked);
       targetUrl  =  "https://datepicker.com/" + dayPicked;
        $(this).change();
      }
    })
    .change(function() {
      alert("Redirect to " + targetUrl);
      //window.location.href = targetUrl;
    });
});
</script>