Home > Web Front-end > JS Tutorial > body text

基于jQuery实现文本框只能输入数字(小数、整数)_jquery

WBOY
Release: 2016-05-16 15:20:04
Original
1159 people have browsed it

在实际应用中,文本框中有时候只能够允许输入整数,但是有时候可能更为"博爱"一点,可以允许输入浮点数,下面就通过实例代码介绍一下如何利用jquery实现文本框只能输入小数,代码如下:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.jb51.net/" />
<title>脚本之家</title>
<script type="text/javascript" src="mytest/jQuery/jquery-1.8.3.js"></script>
<script type="text/javascript">
$(function(){ 
$(".NumText").keyup(function(){ 
$(this).val($(this).val().replace(/[^0-9.]/g,'')); 
}).bind("paste",function(){ 
$(this).val($(this).val().replace(/[^0-9.]/g,'')); 
})
}); 
</script>
</head>
<body>
<input type="text" class="NumText"/>
</body>
</html>
Copy after login

以上代码实现了我们的要求,文本框中只能够输入整数或者浮点数,代码比较简单这里就不多介绍了。

下面给大家介绍如何利用jquery实现文本框只能够输入整数:

有时候可能需要规定文本框内容只能够输入整数,下面给出一段能够实现此功能的代码实例,供需要的朋友参考。

代码如下:

<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="author" content="http://www.jb51.net" />
<title>脚本之家</title>
<script type="text/javascript" src="mytest/jQuery/jquery-1.8.3.js"></script>
<script type="text/javascript">
$(function(){ 
$(".NumText").keyup(function(){ 
$(this).val($(this).val().replace(/\D|^0/g,'')); 
}).bind("paste",function(){
$(this).val($(this).val().replace(/\D|^0/g,'')); 
})
}); 
</script>
</head>
<body>
<input type="text" class="NumText"/>
</body>
</html> 
Copy after login

以上代码实现了预期的要求,文本框中只能够输入整数,下面介绍一下它的实现过程。

代码注释:

1.$(function(){}),当文档结构完全加载完毕再去执行函数中的代码。
2.$(".NumText").keyup(function(){}),为文本框注册keyup事件处理函数。
3.$(this).val($(this).val().replace(/\D|^0/g,'')),通过replace()函数利用正则表达式,将非数字内容替换为空。
4.bind("paste",function(){$(this).val($(this).val().replace(/\D|^0/g,''));}),注册paste事件处理含糊,当然这里使用的是链式调用,它可以防止用户使用ctrl+v方式复制黏贴。

以上代码写的比较简单,部分难点给大家附有注释,相信对大家有所帮助。

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!