I have a Javascript function in Chrome but not in Firefox

Asked

Viewed 154 times

2

I have a javascript function that doesn’t let write numbers, only letters, in Chrome it works exactly as it is proposed, now in Mozilla it doesn’t work, below my function:

function soletra(event) {
    var value = String.fromCharCode(event.which);
    var pattern = new RegExp(/^[a-záàâãéèêíïóôõöúçñ ]+$/i);
    return pattern.test(value);
}

I made an adaptation to work, but it was not good that leaves some keys inactive if the field is in focus:

function soletra(event) {
    if(event.keyCode == 9 || event.keyCode == 8 || event.keyCode == 46
        || event.keyCode == 39 ||event.keyCode == 37 || event.keyCode == 38 || event.keyCode == 40)
        return;
    var value = String.fromCharCode(event.which);
    var pattern = new RegExp(/^[a-záàâãéèêíïóôõöúçñ ]+$/i);
    return pattern.test(value);
}

and the call of function is like this:

$("#id").bind("keypress paste drop", soletra);

1 answer

5


I’ve had this problem with Firefox, after searching the solution I found was to use it:

var key = event.keyCode || event.which;

In the case of Firefox, if the keyCode does not work, uses the which, and also works for other browsers, so you use variable key. I read that in some different keyboard events (keypress, keyup, etc), keyCode does not return a value, it must be the case of your problem.

$("#i1").bind("keypress", function(event) {
  var key = event.keyCode || event.which;
  $("#i2").val(key);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<p>
  <span>Digite aqui:</span>
  <input id='i1' type='text'>
</p>

<p>
  <span>Código da tecla:</span>
  <input id='i2' type='text'>
</p>

See the example in the documentation of Mozilla.org, which has exactly this line of code above: https://developer.mozilla.org/en-US/docs/Web/API/KeyboardEvent

Reference to the OS in English: Event-keycode-not-Working-in-firefox

  • I’m trying to implement this line, but it continue to work in the same way thanks for the help in relation to doc

  • @Brunoh here you can see a functional example: https://jsfiddle.net/jamfLktj/ and I also put an example in the answer

Browser other questions tagged

You are not signed in. Login or sign up in order to post.