开发者

how to detect if wrong key is typed in <input>?

We have a simple html text input: <input type=text /> - al开发者_开发百科l I try to do is add event to fire when user will try to input certaing characters, for example space. So I can alert user while he is typing that these character are not allowed.


to extend rcravens answer a little, I would use the onkeyup event as I have had issues with IE not registering what key fired the event on the onkeydown. You can then process the keycode for the event to determine what actions you want to take.

function getCode(e) {
     var src = get your event however you do so.

     var code = evt.charCode || evt.keyCode;

     switch (code) {
          // do something here.
     }
}

<input type="text" onkeyup="getCode()">

Good resource: Quirksmode.org and here: character codes


Catch both onchange event and onkeyup event. onchange only gets fired when the user tabs to another control. onkeyup will get fired for every typed character. Not sure about when the user pastes something in.

<script>
function OnChangeOccurred(evt) {
    var str = evt.currentTarget.value; // this is the current text in the input box
}
</script>

<input onchange="OnChangeOccurred(event);" onkeyup="OnChangeOccurred(event);" />


Try JavaScript's onkeypress event.

http://www.w3schools.com/jsref/event_onkeypress.asp

This should get you started. You can then intercept all keys and echo their values to determine the ones you want. Be sure to test crossbrowser compliance.

Bob

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜