I don't want to allow a 9 digit number in textbox - javascript

I don't want to allow a 9 digit number in textbox.Textbox should accept alphabets and any number accept a 9 digit number. And the textbox should not except the 9 digit number even if its written in following format: 123-23-2323

Try this:
HTML:
<input type="text" id="txtName" onkeypress="return Allow9NumberOnly(this,event)" />
Jquery:
function Allow9NumberOnly(item, evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode >= 48 && charCode <= 57) {
var myText = $(item).val();
var intCount = 0;
for (var i = 0; i < myText.length; i++) {
if (!isNaN(myText[i])) {
intCount++;
}
}
if (intCount >= 8) {
return false;
}
}
return true;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" id="txtName" onkeypress="return Allow9NumberOnly(this,event)" />
============================================
If you wants to restrict only character 9 then:
function Allow9NumberOnly(item, evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode == 57)
{
return false;
}
return true;
}

Related

Vanilla javascript function to type only numbers not working if not called inline

I have found this function aimed to block the typing of characters that are not numbers:
function isNumber(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
}
If I call it like so: <input class="onlynumbers" type="text" onkeypress="return isNumber(this);" > it works.
If I write something like:
var clickMe = document.querySelectorAll('.onlynumbers');
for (var i = 0; i < clickMe.length; i++) {
clickMe[i].addEventListener('keypress', function (event) {
isNumber(event);
}, false);
}
it does not. I can still type in letters. And I cannot figure out the reason.
Can you please help me with that? Hint: I cannot use JQUERY.
As #VLAZ suggested, using type="number" is a better solution.
However, to fix your code - if the character is not a number use event.preventDefault() to block the letter insertion:
function isNumber(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
}
var clickMe = document.querySelectorAll('.onlynumbers');
for (var i = 0; i < clickMe.length; i++) {
clickMe[i].addEventListener('keypress', function(event) {
if(!isNumber(event)) event.preventDefault();
}, false);
}
<input class="onlynumbers" type="text">

Show error message if non numeric value entered

How to show error message to user if non-numeric values are entered in the text box.
The error message can be displayed below the text box something like enter the numbers only
function isNumber(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
}
<input type="text" class="textfield" onkeypress="return isNumber(event)" />
Just add some sort of output in your if. Like alert or even better, with a message near the input field. But this is up to you.
function isNumber(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
alert("only input numbers");
return false;
}
return true;
}
<input type="text" class="textfield" onkeypress="return isNumber(event)" />
Create a dom element to show the error and add a class to initially hide it. If any input is anything other than number remove the class from the element
function isNumber(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
document.getElementById("errorNumber").classList.remove('error-hide')
return false;
}
document.getElementById("errorNumber").classList.add('error-hide')
return true;
}
.error {
color: red;
}
.error-hide {
display: none;
}
<input type="text" class="textfield" onkeyup="isNumber(event)" />
<p id="errorNumber" class='error error-hide'>Please enter only number </p>
You can use a span element to display the messages inline in the page:
function isNumber(evt) {
var errorClass = document.querySelector('.error');
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
errorClass.style.display = 'block';
return false;
}
errorClass.style.display = 'none';
return true;
}
.error{
display: none;
color: red;
}
<input type="text" class="textfield" onkeypress="return isNumber(event)" />
<span class='error' >Enter numbers only</span>
Seems like your are not considering digits when it's typed from keyboard's 'numpad'.
Following should work.
function isNumber(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || (charCode > 57 && charCode < 96) || charCode > 105)) {
document.getElementById("errorNumber").classList.remove('error-hide')
return false;
}
document.getElementById("errorNumber").classList.add('error-hide')
return true;
}
.error {
color: red;
}
.error-hide {
display: none;
}
<input type="text" class="textfield" onkeyup="isNumber(event)" />
<p id="errorNumber" class='error error-hide'>Please enter only number </p>
function isNumber(evt) {
if(isNaN(evt.key)) {
document.getElementById('inptErr').style.display = "block";
} else {
document.getElementById('inptErr').style.display = "none";
}
}
<input type="text" class="textfield" onkeypress="isNumber(event)" />
<span id="inptErr" style="display:none;color:red;">Please enter numbers only</span>

Change input type of textbox

I am using a script for my textbox to make sure the user can enter only numbers instead of text.
Here is my textbox:
<input type="text" value="" id="tb1" name="tb1" onkeypress="return isNumber(event)" />
And here is my javascript:
function isNumber(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
}
I want to upgrade my JavaScript. I want that the textbox accepts a input with a dot . (only 1 dot), like 11.5
What do I need to change in my script so it will be accept the dot and limit this to one?
Try this one
<input type="text" id="txtCheck" onkeypress="AllowDecimalNumbersOnly(this, event)" />
function AllowDecimalNumbersOnly(Id, Evt) {
Id.value = Id.value.replace(/[^0-9\.]/g, '');
if ((Evt.which != 46 || Id.value.indexOf('.') != -1) && (Evt.which < 48 || Evt.which > 57)) {
Evt.preventDefault();
}
}
JavaScript :
<script>
var isHav=false;
function isNumber(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if(charCode == 46){
if(isHav==true){
return false;
}else{
isHav=true;
return true;
}
}
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
}
</script>
HTML :
<input type="text" value="" id="tb1" name="tb1" onkeypress="return isNumber(event)" />
alternatively you can use this..
function isNumber(evt) {
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode( key );
var regex = /^[0-9.,]+$/;
if( !regex.test(key) ) {
theEvent.returnValue = false;
if(theEvent.preventDefault) theEvent.preventDefault();
}
}
<input type="text" value="" id="tb1" name="tb1" onkeypress="return isNumber(event)" />
Follow the below code:
you need to change your function onkeypress event by adding this parameter
just like below:
<input type="text" value="" id="tb1" name="tb1" onkeypress="return isNumber(event, this)" />
and change your function as below:
function isNumber(evt, element) {
var charCode = (evt.which) ? evt.which : event.keyCode
if ((charCode != 46 || $(element).val().indexOf('.') != -1) && // “.” CHECK DOT, AND ONLY ONE.
(charCode > 31 && (charCode < 48 || charCode > 57)))
{
return false;
}
return true;
}
You can check below running code:
function isNumber(evt, element) {
var charCode = (evt.which) ? evt.which : event.keyCode
if ((charCode != 46 || $(element).val().indexOf('.') != -1) && // “.” CHECK DOT, AND ONLY ONE.
(charCode > 31 && (charCode < 48 || charCode > 57)))
{
return false;
}
return true;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="text" value="" id="tb1" name="tb1" onkeypress="return isNumber(event, this)" />
You can use type="number" attribute if it meet with your requirement
<input type="text" value="" id="tb1" name="tb1" onkeypress="return isNumber(event)" type="number" />
Or Use This
function isNumber(evt)
{
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode != 46 && charCode > 31
&& (charCode < 48 || charCode > 57))
return false;
return true;
}

Javascript Function to enter only alphabets on keypress

I want to enter only character values inside a <textarea> and numeric values in another. I have been able to make a JavaScript function which only allows numeric values to be entered in the <textarea> using onkeypress. This works in Firefox and Chrome.
For alphabets I am creating another JavaScript function using windows.event property. Only problem is this works only in Chrome and not in Firefox.
I want to know how to allow only alphabets to be entered using onkeypress event as used for entering only numeric values?
function isNumberKey(evt){ <!--Function to accept only numeric values-->
//var e = evt || window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode
if (charCode != 46 && charCode > 31
&& (charCode < 48 || charCode > 57))
return false;
return true;
}
function ValidateAlpha(evt)
{
var keyCode = (evt.which) ? evt.which : evt.keyCode
if ((keyCode < 65 || keyCode > 90) && (keyCode < 97 || keyCode > 123) && keyCode != 32)
return false;
return true;
}
<label for="cname" class="label">The Risk Cluster Name</label>
<textarea id="cname" rows="1px" cols="20px" style="resize:none" placeholder="Cluster Name" onKeyPress="return ValidateAlpha(event);"></textarea>
<br>
<label for="cnum">Risk Cluster Number:</label>
<textarea id="cmun" rows="1px" cols="12px" style="resize:none" placeholder="Cluster Number" onkeypress="return isNumberKey(event)"></textarea>
function lettersOnly()
{
var charCode = event.keyCode;
if ((charCode > 64 && charCode < 91) || (charCode > 96 && charCode < 123) || charCode == 8)
return true;
else
return false;
}
<input type="text" name="fname" value="" onkeypress="return lettersOnly(event)"/>
If you don't need to support older browsers I would use the input event. This way you can also catch non-alpha characters if the user pastes text into the textarea.
I cleaned up your HTML a little bit. The most important changes are to the events on cname and cnum. Note that the event in both cases has been changed to oninput.
<label for="cname" class="label"> The Risk Cluster Name</label>
<textarea id="cname" rows="1" cols="20" style="resize:none" placeholder="Cluster Name" oninput="validateAlpha();"></textarea>
<label for="cnum">Risk Cluster Number:</label>
<textarea id="cmun" rows="1" cols="12" style="resize:none" placeholder="Cluster Number" oninput="isNumberKey();"></textarea><br /><br /><br />
Assuming you want cname to only accept characters in the alphabet and cnum to only accept numbers, your JavaScript should be:
function validateAlpha(){
var textInput = document.getElementById("cname").value;
textInput = textInput.replace(/[^A-Za-z]/g, "");
document.getElementById("cname").value = textInput;
}
function isNumberKey(){
var textInput = document.getElementById("cmun").value;
textInput = textInput.replace(/[^0-9]/g, "");
document.getElementById("cmun").value = textInput;
}
This code uses regular expressions, a way to match patterns in strings.
Best Uses
<input type="text" name="checkno" id="checkno" class="form-control" value="" onkeypress="return isNumber(event)"/>
<input type="text" name="checkname" id="checkname" class="form-control" value="" onkeypress="return isAlfa(event)"/>
function isNumber(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
return true;
}
function isAlfa(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 65 || charCode > 90) && (charCode < 97 || charCode > 122)) {
return false;
}
return true;
}
function digitonly(input,event){
var keyCode = event.which ? event.which : event.keyCode;
var lisShiftkeypressed = event.shiftKey;
if(lisShiftkeypressed && parseInt(keyCode) != 9){return false;}
if((parseInt(keyCode)>=48 && parseInt(keyCode)<=57) || keyCode==37/*LFT ARROW*/ || keyCode==39/*RGT ARROW*/ || keyCode==8/*BCKSPC*/ || keyCode==46/*DEL*/ || keyCode==9/*TAB*/ || keyCode==45/*minus sign*/ || keyCode==43/*plus sign*/){return true;}
BootstrapDialog.alert("Enter Digits Only");
input.focus();
return false;
}
function alphaonly(input,event){
var keyCode = event.which ? event.which : event.keyCode;
//Small Alphabets
if(parseInt(keyCode)>=97 && parseInt(keyCode)<=122){return true;}
//Caps Alphabets
if(parseInt(keyCode)>=65 && parseInt(keyCode)<=90){return true;}
if(parseInt(keyCode)==32 || parseInt(keyCode)==13 || parseInt(keyCode)==46 || keyCode==9/*TAB*/ || keyCode==8/*BCKSPC*/ || keyCode==37/*LFT ARROW*/ || keyCode==39/*RGT ARROW*/ ){return true;}
BootstrapDialog.alert("Only Alphabets are allowed")
input.focus();
return false;
}
hi try below code it worked for me in all browsers, it allows numbers and few special characters like,.+-() :
in the textbox use as follows
<asp:Textbox Id="txtPhone" runat="server" onKeyPress="return onlyNumbersandSpecialChar()"> </asp:Textbox>
function onlyNumbersandSpecialChar(evt) {
var e = window.event || evt;
var charCode = e.which || e.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57 || charCode > 107 || charCode > 219 || charCode > 221) && charCode != 40 && charCode != 32 && charCode != 41 && (charCode < 43 || charCode > 46)) {
if (window.event) //IE
window.event.returnValue = false;
else //Firefox
e.preventDefault();
}
return true;
}
</script>

Allow only numbers and dot in script

Am using this javascript for restrict users to type only numbers and only one dot as decimal separator.
<script type="text/javascript">
function fun_AllowOnlyAmountAndDot(txt)
{
if(event.keyCode > 47 && event.keyCode < 58 || event.keyCode == 46)
{
var txtbx=document.getElementById(txt);
var amount = document.getElementById(txt).value;
var present=0;
var count=0;
if(amount.indexOf(".",present)||amount.indexOf(".",present+1));
{
// alert('0');
}
/*if(amount.length==2)
{
if(event.keyCode != 46)
return false;
}*/
do
{
present=amount.indexOf(".",present);
if(present!=-1)
{
count++;
present++;
}
}
while(present!=-1);
if(present==-1 && amount.length==0 && event.keyCode == 46)
{
event.keyCode=0;
//alert("Wrong position of decimal point not allowed !!");
return false;
}
if(count>=1 && event.keyCode == 46)
{
event.keyCode=0;
//alert("Only one decimal point is allowed !!");
return false;
}
if(count==1)
{
var lastdigits=amount.substring(amount.indexOf(".")+1,amount.length);
if(lastdigits.length>=2)
{
//alert("Two decimal places only allowed");
event.keyCode=0;
return false;
}
}
return true;
}
else
{
event.keyCode=0;
//alert("Only Numbers with dot allowed !!");
return false;
}
}
</script>
<td align="right">
<asp:TextBox ID="txtQ1gTarget" runat="server" Width="30px" CssClass="txtbx" MaxLength="6" onkeypress="return fun_AllowOnlyAmountAndDot(this);"></asp:TextBox>
</td>
But the onkeypress(this) event returns object required error in that function at this place
var amount = document.getElementById(txt).value;
What's my mistake here?
This is a great place to use regular expressions.
By using a regular expression, you can replace all that code with just one line.
You can use the following regex to validate your requirements:
[0-9]*\.?[0-9]*
In other words: zero or more numeric characters, followed by zero or one period(s), followed by zero or more numeric characters.
You can replace your code with this:
function validate(s) {
var rgx = /^[0-9]*\.?[0-9]*$/;
return s.match(rgx);
}
That code can replace your entire function!
Note that you have to escape the period with a backslash (otherwise it stands for 'any character').
For more reading on using regular expressions with javascript, check this out:
http://www.regular-expressions.info/javascript.html
You can also test the above regex here:
http://www.regular-expressions.info/javascriptexample.html
Explanation of the regex used above:
The brackets mean "any character inside these brackets." You can use a hyphen (like above) to indicate a range of chars.
The * means "zero or more of the previous expression."
[0-9]* means "zero or more numbers"
The backslash is used as an escape character for the period, because period usually stands for "any character."
The ? means "zero or one of the previous character."
The ^ represents the beginning of a string.
The $ represents the end of a string.
Starting the regex with ^ and ending it with $ ensures that the entire string adheres to the regex pattern.
Hope this helps!
Use Jquery instead. Add a decimal class to your textbox:
<input type="text" class="decimal" value="" />
Use this code in your JS. It checks for multiple decimals and also restrict users to type only numbers.
$('.decimal').keyup(function(){
var val = $(this).val();
if(isNaN(val)){
val = val.replace(/[^0-9\.]/g,'');
if(val.split('.').length>2)
val =val.replace(/\.+$/,"");
}
$(this).val(val);
});​
Check this fiddle: http://jsfiddle.net/2YW8g/
Hope it helps.
Just add the code below in your input text:
onkeypress='return event.charCode == 46 || (event.charCode >= 48 && event.charCode <= 57)'
Instead of using this:
onkeypress="return fun_AllowOnlyAmountAndDot(this);"
You should use this:
onkeypress="return fun_AllowOnlyAmountAndDot(this.id);"
function isNumberKey(evt,id)
{
try{
var charCode = (evt.which) ? evt.which : event.keyCode;
if(charCode==46){
var txt=document.getElementById(id).value;
if(!(txt.indexOf(".") > -1)){
return true;
}
}
if (charCode > 31 && (charCode < 48 || charCode > 57) )
return false;
return true;
}catch(w){
alert(w);
}
}
<html>
<head>
</head>
<body>
<INPUT id="txtChar" onkeypress="return isNumberKey(event,this.id)" type="text" name="txtChar">
</body>
</html>
<input type="text" class="decimal" value="" />
$('.decimal').keypress(function(evt){
return (/^[0-9]*\.?[0-9]*$/).test($(this).val()+evt.key);
});
I think this simple solution may be.
This works best for me.
I also apply a currency formatter on blur where the decimal part is rounded at 2 digits just in case after validating with parseFloat.
The functions that get and set the cursor position are from Vishal Monpara's blog. I also do some nice stuff on focus with those functions. You can easily remove 2 blocks of code where 2 decimals are forced if you want and get rid of the set/get caret functions.
<html>
<body>
<input type="text" size="30" maxlength="30" onkeypress="return numericValidation(this,event);" />
<script language="JavaScript">
function numericValidation(obj,evt) {
var e = event || evt; // for trans-browser compatibility
var charCode = e.which || e.keyCode;
if (charCode == 46) { //one dot
if (obj.value.indexOf(".") > -1)
return false;
else {
//---if the dot is positioned in the middle give the user a surprise, remember: just 2 decimals allowed
var idx = doGetCaretPosition(obj);
var part1 = obj.value.substr(0,idx),
part2 = obj.value.substring(idx);
if (part2.length > 2) {
obj.value = part1 + "." + part2.substr(0,2);
setCaretPosition(obj, idx + 1);
return false;
}//---
//allow one dot if not cheating
return true;
}
}
else if (charCode > 31 && (charCode < 48 || charCode > 57)) { //just numbers
return false;
}
//---just 2 decimals stubborn!
var arr = obj.value.split(".") , pos = doGetCaretPosition(obj);
if (arr.length == 2 && pos > arr[0].length && arr[1].length == 2)
return false;
//---
//ok it's a number
return true;
}
function doGetCaretPosition (ctrl) {
var CaretPos = 0; // IE Support
if (document.selection) {
ctrl.focus ();
var Sel = document.selection.createRange ();
Sel.moveStart ('character', -ctrl.value.length);
CaretPos = Sel.text.length;
}
// Firefox support
else if (ctrl.selectionStart || ctrl.selectionStart == '0')
CaretPos = ctrl.selectionStart;
return (CaretPos);
}
function setCaretPosition(ctrl, pos){
if(ctrl.setSelectionRange)
{
ctrl.focus();
ctrl.setSelectionRange(pos,pos);
}
else if (ctrl.createTextRange) {
var range = ctrl.createTextRange();
range.collapse(true);
range.moveEnd('character', pos);
range.moveStart('character', pos);
range.select();
}
}
</script>
</body>
</html>
function isNumber(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 46 || charCode > 57)) {
return false;
}
return true;
}
you should use this function and write the properties of this element ;
HTML Code:
<input id="deneme" data-mini="true" onKeyPress="return isNumber(event)" type="text"/>`
try This Code
var check = function(evt){
var data = document.getElementById('num').value;
if((evt.charCode>= 48 && evt.charCode <= 57) || evt.charCode== 46 ||evt.charCode == 0){
if(data.indexOf('.') > -1){
if(evt.charCode== 46)
evt.preventDefault();
}
}else
evt.preventDefault();
};
document.getElementById('num').addEventListener('keypress',check);
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<input type="text" id="num" value="" />
</body>
</html>
<script type="text/javascript">
function numericValidation(txtvalue) {
var e = event || evt; // for trans-browser compatibility
var charCode = e.which || e.keyCode;
if (!(document.getElementById(txtvalue.id).value))
{
if (charCode > 31 && (charCode < 48 || charCode > 57))
return false;
return true;
}
else {
var val = document.getElementById(txtvalue.id).value;
if(charCode==46 || (charCode > 31 && (charCode > 47 && charCode < 58)) )
{
var points = 0;
points = val.indexOf(".", points);
if (points >= 1 && charCode == 46)
{
return false;
}
if (points == 1)
{
var lastdigits = val.substring(val.indexOf(".") + 1, val.length);
if (lastdigits.length >= 2)
{
alert("Two decimal places only allowed");
return false;
}
}
return true;
}
else {
alert("Only Numarics allowed");
return false;
}
}
}
</script>
<form id="form1" runat="server">
<div>
<asp:TextBox ID="txtHDLLevel" MaxLength="6" runat="server" Width="33px" onkeypress="return numericValidation(this);" />
</div>
</form>
You can use this
Javascript
function isNumber(evt) {
evt = (evt) ? evt : window.event;
var charCode = (evt.which) ? evt.which : evt.keyCode;
if (charCode > 31 && (charCode < 48 || charCode > 57)&&(charCode!=46)) {
return false;
}
return true;
}
Usage
<input onkeypress="return isNumber(event)" class="form-control">
This function will prevent entry of anything other than numbers and a single dot.
function validateQty(el, evt) {
var charCode = (evt.which) ? evt.which : event.keyCode
if (charCode != 45 && charCode != 8 && (charCode != 46) && (charCode < 48 || charCode > 57))
return false;
if (charCode == 46) {
if ((el.value) && (el.value.indexOf('.') >= 0))
return false;
else
return true;
}
return true;
var charCode = (evt.which) ? evt.which : event.keyCode;
var number = evt.value.split('.');
if (charCode != 46 && charCode > 31 && (charCode < 48 || charCode > 57)) {
return false;
}
};
<input type="text" onkeypress='return validateQty(this,event);'>
Try this for multiple text fileds (using class selector):
Click here for example..
var checking = function(event){
var data = this.value;
if((event.charCode>= 48 && event.charCode <= 57) || event.charCode== 46 ||event.charCode == 0){
if(data.indexOf('.') > -1){
if(event.charCode== 46)
event.preventDefault();
}
}else
event.preventDefault();
};
function addListener(list){
for(var i=0;i<list.length;i++){
list[i].addEventListener('keypress',checking);
}
}
var classList = document.getElementsByClassName('number');
addListener(classList);
<!DOCTYPE html>
<html>
<head>
<title>Page Title</title>
</head>
<body>
<input type="text" class="number" value="" /><br><br>
<input type="text" class="number" value="" /><br><br>
<input type="text" class="number" value="" /><br><br>
<input type="text" class="number" value="" /><br><br>
</body>
</html>
<script type="text/Javascript">
function checkDecimal(inputVal) {
var ex = /^[0-9]+\.?[0-9]*$/;
if (ex.test(inputVal.value) == false) {
inputVal.value = inputVal.value.substring(0, inputVal.value.length - 1);
}
}
</script>
In this function there is an error while editing it when I have added 2 digits(I have defined it's limit 2) after decimal point than it returns false, like if we have to change 1486.00 to 1582.00 without clearing the whole input or deleting any number after decimal point it will return false.
There is a small change required, where the condition of count is 1(count === 1) there add a condition event.target.selectionStart > amount.indexOf(".")
The final code will be
const validDecimal = (event) => {
if ((event.charCode > 47 && event.charCode < 58) || event.charCode === 46) {
var amount = event.target.value;
var present = 0;
var count = 0;
do {
present = amount.indexOf(".", present);
if (present != -1) {
count++;
present++;
}
} while (present != -1);
if (present === -1 && amount.length === 0 && event.charCode === 46) {
event.charCode = 0;
// alert("Wrong position of decimal point not allowed !!");
return false;
}
if (count >= 1 && event.charCode === 46) {
event.charCode = 0;
// alert("Only one decimal point is allowed !!");
return false;
}
if (count === 1 && event.target.selectionStart > amount.indexOf(".")) {
var lastdigits = amount.substring(
amount.indexOf(".") + 1,
amount.length
);
if (lastdigits.length >= 2) {
// alert("Two decimal places only allowed");
event.charCode = 0;
return false;
}
}
return true;
} else {
event.charCode = 0;
// alert("Only Numbers with dot allowed !!");
return false;
}
};
Please try below code. this could help you to solve it.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<script>
function fnAllowNumbersAndDotKey(input, event)
{
var charCode = (event.which) ? event.which : event.keyCode;
if (charCode == 46)
{
//only one dot (.) allow
if (input.value.indexOf('.') === -1)
{
return true;
}
else
{
return false;
}
}
else
{
if (charCode > 31 && (charCode < 48 || charCode > 57))
{
return false;
}
}
return true;
}
</script>
</head>
<body>
<form method='post' >
<input type="text" name='amount' class='form-control' onkeypress="return fnAllowNumbersAndDotKey(this, event);" maxlength="50" />
</form>
</body>
</html>
<input type="text" class="form-control" id="odometer_reading" name="odometer_reading" placeholder="Odometer Reading" onblur="odometer_reading1();" onkeypress='validate(event)' required="" />
<script>
function validate(evt) {
var theEvent = evt || window.event;
var key = theEvent.keyCode || theEvent.which;
key = String.fromCharCode( key );
var regex = /[0-9]|\./;
if( !regex.test(key) ) {
theEvent.returnValue = false;
if(theEvent.preventDefault) theEvent.preventDefault();
}
}
</script>
Hope this could help someone
$(document).on("input", ".numeric", function() {
this.value = this.value.match(/^\d+\.?\d{0,2}/);});

Categories