Home  >  Article  >  How does jquery realize that only numbers and decimal points can be input

How does jquery realize that only numbers and decimal points can be input

尊渡假赌尊渡假赌尊渡假赌
尊渡假赌尊渡假赌尊渡假赌Original
2023-05-29 09:55:491779browse

jquery implements the operation method of inputting only numbers and decimal points: 1. Create an html sample file; 2. Introduce the jQuery file in the head tag; 3. Use "$("input box").keypress() " syntax, to monitor the keyboard, only decimal point and number input is allowed; 4. Use regular expressions to match "/D|^0/g" and replace it with "/[^0-9.]/g".

How does jquery realize that only numbers and decimal points can be input

Operating system for this tutorial: Windows 10 system, jQuery3.6.0 version, Dell G3 computer.

jquery implements the operation method of inputting only numbers and decimal points:

1. Reference the jQuery file in html:

<!DOCTYPE html>
<html>
 <head>
<script src="http://libs.baidu.com/jquery/2.0.0/jquery.js"></script>
</head>
</html>

2. Use the ".keypres()" method to control that the text box with class checkNum can only enter numbers and decimal points:

//监听键盘,只允许输入数字和小数点
$(".checkNum").keypress(function(event) {
var keyCode = event.which;
if (keyCode == 46 || (keyCode >= 48 && keyCode <=57) || keyCode == 8)//8是删除键
return true;
else
return false;
}).focus(function() {
this.style.imeMode=&#39;disabled&#39;;
});

3. Process it through regular expressions:

/*JQuery 限制文本框只能输入数字和小数点*/
$(".NumDecText").keyup(function(){
$(this).val($(this).val().replace(/[^0-9.]/g,&#39;&#39;));
}).bind(
"paste",function(){
$(this).val($(this).val().replace(/[^0-9.]/g,&#39;&#39;)); 
//粘贴的不是数字,则替换为&#39;&#39;    //或 return false; 禁用粘贴功能})
.css("ime-mode", "disabled"); 
//CSS设置输入法不可用

The above is the detailed content of How does jquery realize that only numbers and decimal points can be input. 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