Is there a way to get the current value from a date input field in the keypress event? I have used the jQuery .val() function or the straight javascript .value on text input fields in the keypress event without difficulty, but when I try either of these on a date input field (in a browser that supports it, such as chrome), I just get an empty string – apparently the value isn’t set until a valid date is entered.
I’m using this functionality to allow a user to enter a date as just six digits, such as 110712, and automatically adding the slashes as they type to make 11/07/12. I could, of course, just use a plain text input, but I like the pop-up date picker the date type field gives me on browsers that support it.
EDIT:
Perhaps I wasn’t clear about what I was trying to do. From within the keypress handler attached to a date input field, I want to get what the user has currently typed in the field. For example, if the user has already typed “11” and then types a “0”, I want to be able to see that the current value of the field is “11”. With a basic text input (or a browser not supporting date input fields), I can call .val() or .value from within the keypress event handler and it will give me a result of “11”. In a browser that supports date input fields, however, all I get when calling val() or .value is “”.
Update:
Unfortuantely, it would appear that this cannot be done. Consider the input[type=”date”] a select where the options are every date in history, rather than a textbox.
http://www.html5tutorial.info/html5-date.php
The above link shows other browsers implementing it exactly this way. Notice that as soon as your textbox has a valid date, .val() gets that value.
you could accomplish a hybrid using both an input[type=”text”] and a small input[type=”date”] next to it that dumps its value into the textbox on change.
Working example: http://jsfiddle.net/WaAcU/ (this doesnt do your validation, just dumps the selector into a textbox)
Original Answer:
use the JQuery keypress handler.
trivial example:
http://jsfiddle.net/zUMHr/