Reputation: 1748
how to restrict user to enter only numbers with 6 digits and two decimal values in textbox using javascript??
//Function to allow only numbers to textbox
function validate(key) {
//getting key code of pressed key
var keycode = (key.which) ? key.which : key.keyCode;
var phn = document.getElementById('txtPhn');
//comparing pressed keycodes
if ((keycode < 48 || keycode > 57)) {
return false;
} else {
if (phn.value.length < 6) {
return true;
} else {
return false;
}
}
}
EDIT:
var txtBudget = document.getElementById('MainContent_txtBudget');
txtBudget.addEventListener('input', function (prev)
{
return function (evt) {
if (!/^\d{0,6}(?:\.\d{0,2})?$/.test(this.value)) {
this.value = prev;
}
else {
prev = this.value;
}
};
} (txtBudget.value), false);
Upvotes: 0
Views: 10632
Reputation: 11
**When I Googling, found a code. And then i modify to what i need. And I think it will help you**.
**HTML**
<html>
<head>
<meta charset="utf-8">
<title>JS Bin</title>
</head>
<body>
<input type="text" id="sal" name="sal" onkeypress="return isDecimalNumber(event,this)">
</body>
</html>
**Javascript**
<script type="text/javascript">
function isDecimalNumber(evt, c) {
var charCode = (evt.which) ? evt.which : event.keyCode;
var dot1 = c.value.indexOf('.');
var dot2 = c.value.lastIndexOf('.');
if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57))
return false;
else if (charCode == 46 && (dot1 == dot2) && dot1 != -1 && dot2 != -1)
return false;
return true;
}
</script>
Upvotes: 0
Reputation: 54649
You can try something like this:
var foo = document.getElementById('foo');
foo.addEventListener('input', function (prev) {
return function (evt) {
if (!/^\d{0,6}(?:\.\d{0,2})?$/.test(this.value)) {
this.value = prev;
}
else {
prev = this.value;
}
};
}(foo.value), false);
The code is not cross-browser compliant, but it should give you a hint of how it can be done.
demo: http://jsfiddle.net/v4tGc/
Update: not using the input event.
var foo = document.getElementById('foo');
foo.addEventListener('keypress', function (evt) {
var value = this.value + String.fromCharCode(evt.which);
if (!/^\d{0,6}(?:\.\d{0,2})?$/.test(value)) {
evt.preventDefault();
}
}, false);
Upvotes: 4