views:

33

answers:

2

Hi guys, I have the following code:

http://jsfiddle.net/SPWWx/

I'm completely new to javascript, this is my first time using it. The values of the HTML selects MUST be 01,02 etc, that's why I had to use a big long if else statement. The values have to be submitted to an application on a server, which is extremely fussy about what way it takes in values.

Why won't it set the day as 15 (today) in the select box?

+6  A: 

You have a few issues, you're not including jQuery on the left, the element has a name not an ID or CID, so it needs to be id="CID" or your selector needs to be select[name='CID']. Last, you need to pass a string to .val() to get the result you want, otherwise it's trying to set it to "4", which doesn't equal "04".

You can shorten all your code down to this though:

var day = new Date().getDate().toString();
$("#CID").val(day.length == 1 ? "0" + day : day);​

You can test it here, also as Jamiec points out, you want .getDate() to get the date of the month as opposed to .getDay() which is of the week.

Nick Craver
This is right, and should be the accepted answer. Just to add one thing; use `CurrentDate.getDate()` to get the day number (15 for today).
Jamiec
Nice and comprehensive. I'd just been finding the first two problems, when you'd already sorted it.
chryss
@Jamiec - Missed that error, thanks, and updated.
Nick Craver
Thank you for this :)
Marcus
@Marcus you should mark this as the answer if it has helped you.
Jamiec
One more quick one, for month and year would it be the same idea?
Marcus
@Marcus - Similar yes, but `.getMonth() +1` for month, and `.getFullYear()` for year, here's a full list: http://www.w3schools.com/jsref/jsref_obj_date.asp
Nick Craver
Sorry again Nick, would this be it?http://jsfiddle.net/nz2Uu/2/
Marcus
@Marcus - Almost :) `.getMonth()` is 0-11, so you need a +1 like this: http://jsfiddle.net/nz2Uu/3/
Nick Craver
Thank you so much for your help, saved me a lot of time.
Marcus
A: 

because the element's name is CID, not it's id! $('#CID') selects the element with the id CID.

Robbert