Home  >  Article  >  Web Front-end  >  Introduction to the method of realizing that the text box can only enter numbers in JavaScript

Introduction to the method of realizing that the text box can only enter numbers in JavaScript

黄舟
黄舟Original
2017-12-04 13:28:543289browse

在我们日常开发中,为了更好的给用户带来体验,我们有的时候需要限制文本框输入内容的类型,这里我们很多时候都会使用到正则表达式来完成,今天我们就给大家介绍下JavaScript实现文本框只能输入数字、小数点、英文字母、汉字等代码。

例如,输入大于0的正整数
代码如下:

1,文本框只能输入数字代码(小数点也不能输入)

代码如下:

2,只能输入数字,能输小数点.

代码如下:


3,数字和小数点方法二
 代码如下:

封装成单独的函数:
 代码如下:

function keyPress(ob) {
 if (!ob.value.match(/^[\+\-]?\d*?\.?\d*?$/)) ob.value = ob.t_value; else ob.t_value = ob.value; 
 if (ob.value.match(/^(?:[\+\-]?\d+(?:\.\d+)?)?$/)) ob.o_value = ob.value;
}
function keyUp(ob) {
 if (!ob.value.match(/^[\+\-]?\d*?\.?\d*?$/)) ob.value = ob.t_value; else ob.t_value = ob.value; 
 if (ob.value.match(/^(?:[\+\-]?\d+(?:\.\d+)?)?$/)) ob.o_value = ob.value;
        }
function onBlur(ob) {
if(!ob.value.match(/^(?:[\+\-]?\d+(?:\.\d+)?|\.\d*?)?$/))ob.value=ob.o_value;
else{if(ob.value.match(/^\.\d+$/))ob.value=0+ob.value;
if(ob.value.match(/^\.$/))ob.value=0;ob.o_value=ob.value};
}

只需在调用,传入this对象即可!

4,只能输入字母和汉字

代码如下:

5,只能输入英文字母和数字,不能输入中文

代码如下:

6,只能输入数字和英文

代码如下:

7,小数点后只能有最多两位(数字,中文都可输入),不能输入字母和运算符号:

代码如下:

8,小数点后只能有最多两位(数字,字母,中文都可输入),可以输入运算符号:

代码如下:

总结:

本文使用JavaScript代码限制文本框中只能输入数字的多个实例,学如何使用JavaScript控制文本框中输入数字的方法,希望对你的工作有所帮助!

相关推荐:

利用JS让文本框只能输入数字的方法实例代码

限制文本框只能输入数字,小数点,英文字母,汉字

js限制文本框只能输入数字(正则表达式)

The above is the detailed content of Introduction to the method of realizing that the text box can only enter numbers in JavaScript. For more information, please follow other related articles on the PHP Chinese website!

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