Duane
Duane

Reputation: 4499

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

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

Upvotes: 6

Views: 1218

Answers (3)

Maksim Vi.
Maksim Vi.

Reputation: 9225

You can do it with javascript easily. Just check for a selected drop-down box (onfocus) and keypress, if 1 is pressed then select the first element, 2 - second and so on. May also need to add some delay and wait for a second keypress in case of multiple digit numbers.

Alternatively you can try something not standard:

<label for="state">State:</label>
<select id="state" name="state">
    <option accesskey="1">.1.</option>
    <option accesskey="2">.2.</option>
    <option accesskey="3">.3.</option>
    <option accesskey="4">.4.</option>
</select>

By pressing Alt+Number you will be able to select elements in the drop-down. Just add accesskey attribute to the options dynamically (JavaScript) to your focused drop-down box.

Upvotes: 0

Matthew
Matthew

Reputation: 48284

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.

Upvotes: 2

NikiC
NikiC

Reputation: 101936

There is an accesskey attribute in HTML, which allows specifying to allow access using [Alt] + Character. But I don't know, whether this works for <option>:

<select>
    <option accesskey="1">January</option>
    <!-- ... -->
</select>

Upvotes: 0

Related Questions