English 中文(简体)
Mootools 中键盘上的停止事件无效
原标题:Stop event on keyup in mootools doesn t work

I m trying to prevent non-numeric characters being entered in a text field. My code validates the characters but doesn t stop it being added to text box.

我的代码:

var isNumberKey = function(e){
    //alert(e.which);
    if (e.which > 31 && (e.which < 48 || e.which > 57)) 
        return false;   
    return true;
}

var isBackSpaceKey = function(e){
    return e.which == 8;
}

var isArrowKey = function(e) {
    return e.which >= 37 && e.which <= 40;
}

var inputs = $$( .numberOnly );
inputs.addEvent( keyup , function(e){
    console.log(e.which);
    if (!isNumberKey(e) && !isBackSpaceKey(e) && !isArrowKey(e)){
        e.stop();
        return false;
    }
    return true;
});

HTML :

<input name="t1" type="text" class="numberOnly" id="t1"/>
最佳回答

您应该使用 keydown 事件, 而不是 keyup 事件。

var inputs = $$( .numberOnly );
inputs.addEvent( keydown , function(e){
    if (e.code >= 48 && e.code <= 57 ){
        return true;
    }
    e.stop();
    return false;
});

http://jsfiddle.net/TsAkb/

希望这有帮助

<强度 > EDIT:

您也许想要允许“ tab” 键、 “ 输入” 键和“ 后空” 也 = P

问题回答

暂无回答




相关问题
Listen for Events from Browser "Find" Window in JavaScript

Is there a way to listen for typing into the browser s "find" window in JavaScript? (source: apple.com) I d like to be able to reinterpret the search text from JavaScript. What do I need to ...

Equivalent of PreviewKeyDown of C# needed for native C++/MFC

I used a ActiveXControl in a C# Forms application and had the possibility to implement a PreviewKeyDown event handler for that ActiveXControl. That was needed to specify that, e.g. the [ALT] key, is ...

Refresh the UI in gwt

I have created some custom composite widget, which listens to an events (in my case loginEvent). Once the event is caught the state of the widget changes so as the way it should look (in my case I ...

How to remove "onclick" with JQuery?

PHP code: <a id="a$id" onclick="check($id,1)" href="javascript:void(0)" class="black">Qualify</a> I want to remove the onclick="check($id,1) so the link cannot be clicked or "check($id,...

热门标签