debin February 2016

Get keycode/key from string

I have select tag in which I am giving option from F1 to F10..Now when user press button any one from F1 to F10 then I have to detect.

<select id="forward_ckey">
    <option value="default"></option>
    <option value="ESC" disabled>ESC</option>
    <option value="F1">F1</option>
    <option value="F2" disabled>F2</option>
    <option value="F3" selected>F3</option>
    <option value="F4" disabled>F4</option>
    <option value="F5" disabled>F5</option>
    <option value="F6">F6</option>
    <option value="F7">F7</option>
    <option value="F8">F8</option>
    <option value="F9">F9</option>
    <option value="F10">F10</option>
    <option value="F11">F11</option>
    <option value="F12">F12</option>

    $(document).unbind('keydown.g').bind('keydown.g', function (e) {
        var unicode = e.keyCode;            
        if (unicode == 'SELECTED VALUE KEYCODE') { //HERE "F3" KEYCODE

Output: If I press F3 and selected value is also F3 then it should execute code block in that.. The main problem I am facing is that I got F3 from option value and getting keycode from keypress how to match both..Either I need key of pressed from keyboard or keycode of selected value from option


           var selected_id = "";
           $('select').on('change', function() {
             selected_id = this.value;
           $(document).bind('keydown', function(e) {
             var unicode = e.keyCode;
             if (unicode == selected_id) { //F3 KEYCODE or Key from `e`


mjsarfatti February 2016

To get the keycode of the corresponding selected value you need something like this:

var keycodes = {'F1': 112, 'F2': 113, 'F3': 114, …};
var selectedValue = $('#forward_ckey').val();
var selectedKeycode = keycodes[selectedValue];

narainsagar February 2016

This might help:

Here's the sample:

function myKeyboard(e) {
    // gets called when any of the keyboard events are overheard
    keyCode = e.characterCode;

Bind the above function myKeyboard() on your element OR any other input / textarea box.

Also here's list of the keys and their character codes:

Also there's an other helpful guide as well:

check this demo out:

Post Status

Asked in February 2016
Viewed 2,867 times
Voted 6
Answered 2 times


Leave an answer