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

How to implement the function of inputting only two decimal places in javascript

青灯夜游
Release: 2023-01-11 09:18:59
Original
6884 people have browsed it

Method: 1. Add "oninput="value=value.toString().match(/^\d (?:\.\d{0,2})?/)" in the input tag " statement is sufficient. 2. Bind the onimput event to the input tag and use regular expressions in the processing function.

How to implement the function of inputting only two decimal places in javascript

The operating environment of this tutorial: windows7 system, javascript version 1.8.5, Dell G3 computer.

javascript restricts the input box to only numbers with two decimal places

##Method 1:

<input type="number" oninput="value=value.toString().match(/^\d+(?:\.\d{0,2})?/)">
Copy after login

How to implement the function of inputting only two decimal places in javascript

Only two decimal places can be entered.

Method 2: Bind the onimput event to the input tag. In the event processing function, use regular expressions to

Implement code one:


<input type="number" id="put" >
<script type="text/javascript">
var vv = "";
document.getElementById("put").oninput=function(){
	var val = this.value.replace(/\./,"");
	var valArr=this.value.split(&#39;.&#39;);
	if((/\D/g).test(val)||valArr.length>2||valArr.length>1&&Number(valArr[1])>99){
		this.value=vv;
	}
}
</script>
Copy after login

How to implement the function of inputting only two decimal places in javascript

Implementation code two:

<input type="number" id="put">
<script type="text/javascript">
var vv = "";
document.getElementById("put").oninput=function(){
	if(!(/^\d+(.\d{0,2})?$/).test(this.value)){
		this.value=vv;
	}
	vv.this.value;
	return false;
}
</script>
Copy after login

How to implement the function of inputting only two decimal places in javascript

[Recommended learning:

javascript advanced tutorial]

The above is the detailed content of How to implement the function of inputting only two decimal places in javascript. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
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!