0

<select id=SomeDropdown>
  <option value="0">Nothing Here</option>
  <option value="1">- Requirement Analysis</option>
  <option value="2">- - Training & Self Learning</option>
  <option value="3">- - - Bug Fixing</option>
<select>

Notice that the option value/text may contains some characters:

  1. single quotes(')
  2. hyphen (-) /double hyphens (- -)

When keyboard is used to select Bug fixing it selects none but works using -.

What is the correct way to escape characters (in my case hyphens) and allow user to select values from dropdown usign keyboard ?

Surreal Dreams
  • 26,055
  • 3
  • 46
  • 61
Slimshadddyyy
  • 4,085
  • 5
  • 59
  • 121

1 Answers1

0

Without using a plugin this can be tricky. I ended up using a timeout fired on keyup and reset on keydown (ref Run javascript function when user finishes typing instead of on key up?)

The logic is that the timeout handle the writing process, when stop, using jQuery search for the first option element that starts with the chars wrote and set it as selected.

Code:

//setup before functions
var typingTimer;               //timer identifier
var doneTypingInterval = 500;  //time in ms, 5 second for example
var keyText='';

//on keyup, start the countdown
$('#SomeDropdown').keyup(function(e){
    clearTimeout(typingTimer);
    keyText+=String.fromCharCode(e.which);
    typingTimer = setTimeout(doneTyping, doneTypingInterval);
});

//on keydown, clear the countdown 
$('#SomeDropdown').keydown(function(e){
    clearTimeout(typingTimer);    
});

//user is "finished typing," do something
function doneTyping () {

    console.log(keyText)
    $("#SomeDropdown option").filter(function() {
        return this.text.replace(/(\-\s)/gi, '').toUpperCase().lastIndexOf(keyText, 0) === 0; 
    }).attr('selected', true);

    keyText='';
}

Known issues:

  • back space open the select option and break the logic
  • when opened the select, custom typing is not recognized, it use the built in one

Demo: http://jsfiddle.net/th6oxfaq/

Community
  • 1
  • 1
Irvin Dominin
  • 30,819
  • 9
  • 77
  • 111