Skip to content
Advertisement

Mirroring input content with non-printable chars like CTRL, ALT or shift key

When non-printable char is pressed, it’s replaced with let’s say for CTRL=17 with “[CTRL]”. Here is code an example

JavaScript

the problem is when user presses backspace the second input must reflect the content of the first one, so “[CTRL]” must be deleted at once like any other chars.

Advertisement

Answer

You could make use of the keyCode and/or in combination with charCode (if required). Basic idea would be:

  1. Create a map of all required key codes in an array/object
  2. Handle event for say keydown and listen for keycode
  3. Look for the keycode in your map and if found show it
  4. prevent the default (to prevent e.g. say backspace browsing back)
  5. If not found in map, let the character go thru as usual.

A very basic example:

Demo: http://jsfiddle.net/abhitalks/L7nhZ/

Relevant js:

JavaScript

Edit: (as per the comments)

The concept remains the same, just copying the value to the second input:

Demo 2: http://jsfiddle.net/abhitalks/L7nhZ/3/

JavaScript

Regarding deletion of the description, I could not get it done by caching the last inserted descrition from the map. Somehow, I kept struggling with the regex with a variable. Anyway, a simpler solution is to just add another event handler for keyup with hard-coded map.

Thanks to @serakfalcon for (that simple solution), which we are using here:

JavaScript
User contributions licensed under: CC BY-SA
7 People found this is helpful
Advertisement