移动键和Tab键在带有事件onKeypress()JavaScript的Firefox中不起作用

时间:2018-09-25 15:04:56

标签: javascript keypress

我有下一个代码:

function valid_num(e){
    tecla = (document.all) ? e.keyCode : e.which;

    //Tecla de retroceso para borrar, siempre la permite
    if (tecla==8){
        return true;
    }

    //Allows only numbers
    patron =/[0-9]/;
    tecla_final = String.fromCharCode(tecla);
    return patron.test(tecla_final);
}
function valid_text(e){
    tecla = (document.all) ? e.keyCode : e.which;

    //Tecla de retroceso para borrar, siempre la permite
    if (tecla==8 || tecla == 32){
        return true;
    }

    // Allows only letters
    patron =/[a-z,A-Z,ñ,Ñ,á-ú,Á-Ú]/;
    tecla_final = String.fromCharCode(tecla);
    return patron.test(tecla_final);
}
function valid_numText(e){
    tecla = (document.all) ? e.keyCode : e.which;

    //Tecla de retroceso para borrar, siempre la permite
    if (tecla==8){
        return true;
    }

    // Allows numbers and letters
    patron =/[a-z,A-Z,0-9,ñ,Ñ]/;
    tecla_final = String.fromCharCode(tecla);
    return patron.test(tecla_final);
}

这就是我调用函数的方式:

<input id="nombre" name="nombre" type="text" class="validate" onkeypress="return valid_text(event)" maxlength="20" value="<?=$nombre;?>">

这在Chrome中效果很好,但是当我在Firefox中打开同一页面时,它无法检测到Tab键和移动键。 如果有人可以帮助我,我将不胜感激。

2 个答案:

答案 0 :(得分:0)

只需将onkeypress更改为onkeydown
所以你的函数调用变成了

它可以在所有浏览器上正常工作

<input id="nombre" name="nombre" type="text" class="validate" onkeydown="return valid_text(event)" maxlength="20" value="10">

Jsbin链接:https://jsbin.com/qodadey/edit?html,js,console,output

编辑:

要阻止数字或数值以触发函数,请使用条件检查键值并返回false

示例:

  if(e.key <= 9){
  return false;}

答案 1 :(得分:0)

我仅将tecla==0添加到每个条件中就解决了我的问题,例如:

function valid_text(e){

        /*code*/
        if (tecla==8 || tecla == 32 || tecla == 0){
           return true;
        }
        /*code*/

 }

无论如何,谢谢您的帮助

相关问题