Home >Web Front-end >JS Tutorial >How to implement the function of inputting only two decimal places in javascript

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

青灯夜游
青灯夜游Original
2021-09-09 15:08:017078browse

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})?/)">

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>

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>

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!

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