Get the selected date from a dropdown using JavaScript

Go To StackoverFlow.com

0

What I have is a JAVA Script which displays 3 dropdown windows for day, month and year resp. The today’s date is selected by default. The script comes original from: http://www.javascriptkit.com/script/script2/curdateform2.shtml

What I want to add is following:

1) Say the default or selected date is 2012-02-15. I want a text to appear says: "The selected date is: 2012-02-15"

2) I also want to calculate the selected date+30days and also be displayed in similar manner. I have been writing php, mysql codes with god results so far. But I have to say my knowledge is JavaScript is very limited. Thanks!

Hello Chris!

I tried your second suggestion

var day = document.getElementById('daydropdown').value;
var month = document.getElementById('monthdropdown').value;
var year = document.getElementById('yeardropdown').value;
var date_object = new Date();
var ts = Date.parse(year+'-'+month+'-'+day);
document.getElementById('d1').innerHTML = 'The selected date is: '+ date_object.setTime(ts);

I also added in the body:

<div style="font-weight:bold" id="d1" ></div>

But all I get is ... The selected date is: NaN

In the original code the function is activated using window.onload. As far I can understand the code doesn't react when the dropdown lists are used and the date is changed... Now can I solve this?

2012-04-03 21:15
by user1138626


0

If you did not change the element IDs from the sample:

var day = document.getElementById('daydropdown').value;
var month = document.getElementById('monthdropdown').value;
var year = document.getElementById('yeardropdown').value;

// if you simply want to display it:
var text = 'The selected date is: '+year+'-'+month+'-'+day;
alert(text);

// if you want to work with it, make a Date object
var date_object = new Date();
var ts = Date.parse(year+'-'+month+'-'+day);

// javascript dates are in miliseconds, 1 day = 86400 seconds, so...
var thirty_days = 86400 * 1000 * 30;
date_object.setTime(ts + thirty_days);

See the documentation: https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/Date

2012-04-03 21:24
by Chris Baker
Ads