Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is there a clean HTML way to relate a key press to a dropdown item

Tags:

html

jquery

php

I am working on an application in which I want to allow for quick data entry. So I want to make a date field selected by int month value (ie 7 = July). I think I only have 2 options.

  1. Prepend the number to the Month (1 -- Jan, 2 -- Feb, ... etc) but this is Ugly
  2. Use JS or jQuery to intercept key presses and select the appropriate month (doable, but messy)

Is there a way to have a hidden locater for a drop down?

-- Edit for Clarity --

I am trying to allow users to input the date through the keyboard more easily so instead of using a calendar picker (which I have) they could type .... 1 tab 1 tab 2010, which would result in the date Jan 1st, 2010

like image 905
Duane Avatar asked Nov 05 '22 08:11

Duane


1 Answers

Here's an example of how to get it working:

$(function()
{
    $.each($("select.month"), function() { new MonthSelector(this); });
});

var MonthSelector = function(that)
{
    var self = this;
    $(that).bind("keypress", function(event) { self.onKeyPress(event); } );
    this.two = false;
    this.select = that;
};

MonthSelector.prototype.onKeyPress = function(event)
{
    if (event.which < 48 || event.which > 57) return;
    var digit = event.which - 48;

    if (this.two && digit <= 2)
    {
        digit += 10;
        this.two = false;
    }
    else
    {
        this.two = (digit == 1);
    }

    if (digit != 0) 
        this.select.selectedIndex = digit - 1; 
};

It's hard coded to work with 1-12 for simplicity's sake. (The date and year drop downs should automatically work by virtue of the browser's built in functionality.)

This also shouldn't affect the user's ability to (e.g.) type "Dec" for December.

like image 58
Matthew Avatar answered Nov 09 '22 04:11

Matthew