views:

38

answers:

1

Hi Folks,

I recently tried to mirror some input within input(text) fields. Using

 String.fromCharCode(event.which)

for instance, translates all 'standard' characters correctly. Well it translates them all to uppercase, but that you can easily catch by looking up the shift key aswell.

My Problem is, it can't translate characters like dots, commas, questionmarks etc. First guess was that I have to define a character encoding set, but that does not seem to help. Maybe it'm completly off?

Kind Regards

--Andy

+2  A: 

I think you are using the keyup or keydown events, in those events you get actually the key what was pressed, not the actual character, e.g. if the user presses a or A, you will get 65 as the key code.

You should use the keypress event in order to know the exact character that was pressed, e.g.:

document.getElementById('inputId').onkeypress = function (e) {
  e = e || window.event;
  var keyCode = e.keyCode || e.which;
  alert(keyCode);
};

Check a live example here. ​

CMS
@jAndy: If they are simple text fields, you might want also consider to copy the whole value of one input to the other, [e.g.](http://jsbin.com/avuzi3/4) `$('#input1').keyup(function () { $('#input2').val(this.value); });`
CMS
Note that this will still not give you the character being inserted in many cases; you'll often get `0` for valid characters, and special keys will be misreported as codes that clash with real char codes. The whole key handling thing in JavaScript is pretty much a total disaster. Don't rely on it.
bobince