Home >Common Problem >How does jquery realize that only numbers and decimal points can be input
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".
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='disabled'; });
3. Process it through regular expressions:
/*JQuery 限制文本框只能输入数字和小数点*/ $(".NumDecText").keyup(function(){ $(this).val($(this).val().replace(/[^0-9.]/g,'')); }).bind( "paste",function(){ $(this).val($(this).val().replace(/[^0-9.]/g,'')); //粘贴的不是数字,则替换为'' //或 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!