Kevin Brown
Kevin Brown

Reputation: 12650

jQuery Countdown error: returning NaN

I'm using this jQuery countdown plugin: http://keith-wood.name/countdown.html

I'm trying this to set the countdown date:

var countdownValue = $('#countdown-value').text();
alert(countdownValue);
var newYear = new Date(countdownValue); 
$('#countdown-l').countdown({until: newYear}); 

Div to set value:

<div id="countdown-value" style="display:none">2011, 07-1, 13</div>

The alert is returning '2011, 07-1, 13'.

That's what I have entered in the db, so that's correct. But the countdown is returning NaN for each number. However, if I directly enter 2011, 07-1, 13, I get a working countdown. Are there hidden characters, or is this parsed a different way?

I'm kinda lost here. Any thoughts?

Upvotes: 0

Views: 1672

Answers (1)

Andrew Whitaker
Andrew Whitaker

Reputation: 126042

The problem is that when you instantiate a Date object like this:

new Date(2011, 07-1, 13)

(By the way, the 07-1 just resolves to 6, not sure if this is intended)

You're calling the Date constructor with the following version:

new Date(year, month, day)

This is successful, because it creates a valid date. When you call the Date constructor with $('#countdown-value').text(), you are initializing a new Date with the version that takes a string, essentially:

new Date("2011, 07-1, 13")

Which is not a valid date string.

To fix this, you can either make the date you are retrieving a valid date string, or parse out the values (Note that to make this method work easily, you'll have to change 07-1 to "6"):

var countdownValue = $('#countdown-value').text();
var values = countdownValue.split(",");

alert(countdownValue);
var newYear = new Date(parseInt(values[0], 10), parseInt(values[1], 10), parseInt(values[2], 10)); 
$('#countdown-1').countdown({until: newYear }); 

http://jsfiddle.net/vtFkd/

Upvotes: 2

Related Questions