I have a Javascript function that works in Chrome but not in Firefox

2

I have a javascript function that does not let you write numbers, only letters, in chrome it works exactly as it is proposed, now in mozilla it does not 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 function call looks like this:

$("#id").bind("keypress paste drop", soletra);
    
asked by anonymous 10.01.2018 / 11:31

1 answer

5

I already had this problem with Firefox, after researching the solution I found was using this:

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

For Firefox, if keyCode does not work, use which , and also works for other browsers, so you use% var key . I read that in some key keyboard events (keypress, keyup, etc.), keyCode does not return a value, should be the case for 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>Digiteaqui:</span><inputid='i1'type='text'></p><p><span>Códigodatecla:</span><inputid='i2'type='text'></p>

Seetheexampleinthemozilla.orgdocumentation,whichhasexactlythislineofcodeabove: link

OS reference: event-keycode-not-working- in-firefox

    
10.01.2018 / 12:30