Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to change characters typed in Firefox

I need to change in a text input the character '.' to ',' while typing. In IE I change the keyCode event property in the keypress event, like this

document.getElementById('mytext').onkeypress = 
 function (evt) {
  var e = evt || window.event;
  if (e.keyCode && e.keyCode==46)
   e.keyCode = 44;
  else if (e.which && e.which==46) {
   e.which = 44;
  }
 };

but it seemes that in Firefox it's impossible to change characters typed in key events. Any suggestions?

like image 821
Pier Luigi Avatar asked Oct 20 '08 12:10

Pier Luigi


1 Answers

Try this. It works on all browsers:

window.onload = function () {
    var input = document.getElementById("mytext");

    input.onkeypress = function () {
        var evt = arguments[0] || event;
        var char = String.fromCharCode(evt.which || evt.keyCode);

        // Is it a period?
        if (char == ".") {
            // Replace it with a comma
            input.value += ",";

            // Cancel the original event
            evt.cancelBubble = true;
            return false;
        }
    }
};

Update: Pier Luigi pointed out a problem with the above. It doesn't take care of the caret position not being at the end of the text. It will append the command to the end even if you're inserting some text to the value.

The solution would be, instead of appending a comma, to simulate a keypress event for the comma key. Unfortunately the way dispatching of synthetic events work in different browsers seems to show a lot of variety and isn't an easy feat. I'll see if I can find a nice and generic method for it.

like image 70
Ates Goral Avatar answered Oct 11 '22 05:10

Ates Goral