Rotan075
Rotan075

Reputation: 2615

Change date with keycontrols

Hello I got a question regarding changing the date with the arrow keys on your keyboard (keycode 37,38,39,40).

If you look at this example: DatePicker from Telerik they have build a quite nice feature and I was wondering if that also could be achieved with for example the jQuery UI Datepicker widget.

I know that the DatePicker UI does not provide any of this implementation but I was wondering if anyone could guide me into a direction where I can extend the current functionality? Any thoughts always helps!!

Upvotes: 0

Views: 47

Answers (1)

onzinsky
onzinsky

Reputation: 591

Interesting idea! Check out this JsFiddle I just started.

Right now it partially works. First thing I need to fix is I'm not checking the limits (Feb 30 or even Feb 0 or -1 don't exist and I'm not checking that).

Another thing to do is add a "0" if the value is < 10, so the output date right now is "5/12/2016" where it should be "05/12/2016". This does not "break" anything but it would be better I think.

To explain the jsFiddle a bit

Use $("#datepicker-1").on('keydown'... to handle the keydown event.

Inside it, use this.selectionStart; to check the cursor position inside your input.

To avoid going all the way to the start or the end when user presses up or down keys, use:

switch(e.keyCode){
case 38:
  e.preventDefault();
  ...
case 40:
  e.preventDefault();
  ...

Also, do this before exiting the event handler function. Otherwise the cursor goes to the end of the input when pressing the up or down keys.

this.selectionStart = currentPosition;
this.selectionEnd = currentPosition;

I'm still working on it. For now at least, it's very simplistic, but you asked for guides, directions or thoughts so I think this might be useful to you, just to play around a bit at least.

P.S. It's probably a good idea to handle the dates with javascript Date object. I'll get to it.

Upvotes: 1

Related Questions