Home  >  Article  >  Web Front-end  >  js example code that blocks keys in the input box and can only type numbers

js example code that blocks keys in the input box and can only type numbers

PHPz
PHPzOriginal
2016-05-16 17:05:321036browse

This article mainly introduces the js sample code that blocks keys in the input box and can only type numbers. Friends in need can come here for reference. I hope it will be helpful to everyone.

<script language="javascript">
function GetInput(){//屏蔽非数字和非退格符
    var k = event.keyCode;   //48-57是大键盘的数字键,96-105是小键盘的数字键,8是退格符←
    if ((k <= 57 && k >= 48) || (k <= 105 && k >= 96) || (k== 8)){
     return true;
    } else {
     return false;
    }
}
function Set(obj){
   //即时处理输入框的内容,比如进行某些运算
}
</script>
<input type=&#39;text&#39; value=&#39;1&#39; onkeydown=&#39;return GetInput()&#39; onkeyup=&#39;Set(this)&#39; >

Technical essentials: The onkeydown event is triggered before the onkeyup event; when the onkeydown event returns false, the onkeyup event will not be triggered, and the input box There will not be the character that the user just pressed, thus achieving the purpose of blocking certain characters. After understanding the triggering principle of this event, we should extend our thinking (for example, several mouse events will also have such a mechanism)...                                                                                                                                                                                                  

The above is the entire content of this chapter. For more related tutorials, please visit JavaScript Video Tutorial!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn