Jimmy
Jimmy

Reputation: 12497

Pass out date from one function to the the next

I'm trying to write a function which gets called by a button, then reaches out to another function (fetchTime) which returns the time, to be alerted in a box from the first button.

var today;

$(document).ready(function() {
  $(".btn").click(function() {
    fetchTime();
    alert(today);
  });
});


function fetchTime() {
  var today = new Date();
  var dd = today.getDate();
  var mm = today.getMonth() + 1;
  var yyyy = today.getFullYear();
  if (dd < 10) {
    dd = '0' + dd;
  }
  if (mm < 10) {
    mm = '0' + mm;
  }
  var today = yyyy + '-' + mm + '-' + dd;
  return(today);
}

When I run this I get "undefined" alerted in the box. What am I doing wrong here? Also do I have to define today as a global variable at the top.

http://jsfiddle.net/spadez/hc49qes3/2/

Upvotes: 0

Views: 31

Answers (1)

Will
Will

Reputation: 492

fetchTime is returning a value, but you're not storing that value anywhere

The button callback should look like:

today = fetchTime();
alert(today);

Updated fiddle:

http://jsfiddle.net/ed3758cm/

Upvotes: 1

Related Questions