Solved

accept only numbers and one decimal

Posted on 2011-02-24
10
969 Views
Last Modified: 2013-12-13

Hello!

I've been looking everywhere for a javascript function that will allow only numbers and one decimal.

I have a script that allows only numbers and multiple decimals.

function isNumberKey(evt)
      {
         var charCode = (evt.which) ? evt.which : event.keyCode
         if ((charCode > 45 && charCode < 58) || charCode == 8){  
        return true;  
    }  
    return false;
      }

Open in new window


But it would be nice to restrict it.

So far, the most success, I've had is here, but I don't like that because it allows a user to see the character he or she has typed for a split-second before they are erased.

Additionally, I really can't use the input masking features I've seen in some jquery solutions, because that a user will use a decimal is not certain. Only, if he or she does, there must be only one. The masking is for much more stringent data collection I think.

Has anyone seen a script or can author a script that can do this elegantly?

Thank you so much for your help!
0
Comment
Question by:hibbsusan
10 Comments
 
LVL 39

Accepted Solution

by:
Pratima Pharande earned 250 total points
ID: 34977380
try this
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title></title>
<meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1">
<meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
<script language=javascript type=text/javascript  >
function numbersonly(e) {
var key;
var keychar;

if (window.event) {
   key = window.event.keyCode;
}
else if (e) {
   key = e.which;
}
else {
   return true;
}
keychar = String.fromCharCode(key);

if ((key==null) || (key==0) || (key==8) ||  (key==9) || (key==13) || (key==27) ) {
   return true;
}
else if ((("0123456789").indexOf(keychar) > -1)) {
   return true;
}
else if (keychar == ".") { 
  return true;
}
else
   return false;
}

</script> 
</head>
<body >

<form ID="Form1">
  <input name="number"  onKeyPress="return numbersonly(event)" ID="Text1">
</form>

</body>
</html>

Open in new window

0
 
LVL 16

Expert Comment

by:sjklein42
ID: 34977390
You like what you have already with isNumberKey, but you would like it to restrict to a single decimal point.  Is that right?

If that's the problem, my suggestion would be:

Within your isNumberKey function you could add a line of code that first fetches the current value of the input field, checks to see if it already contains a decimal point, and decides on the fly whether charCode 8 (I'm guessing that's the dot) should be allowed at that moment, for that keystroke.

Or did I miss the point?
0
 
LVL 16

Expert Comment

by:sjklein42
ID: 34977427
Combining pratima_mcs: with a variation to restrict to a single decimal point, we get this:
 
<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title></title>
<meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1">
<meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
<script language=javascript type=text/javascript  >

function getTarget(e) {
	var targ;
	if (!e) var e = window.event;
	if (e.target) targ = e.target;
	else if (e.srcElement) targ = e.srcElement;
	if (targ.nodeType == 3) // defeat Safari bug
		targ = targ.parentNode;
	return targ;
}


function numbersonly(e) {
var key;
var keychar;

if (window.event) {
   key = window.event.keyCode;
}
else if (e) {
   key = e.which;
}
else {
   return true;
}
keychar = String.fromCharCode(key);

if ((key==null) || (key==0) || (key==8) ||  (key==9) || (key==13) || (key==27) ) {
   return true;
}
else if ((("0123456789").indexOf(keychar) > -1)) {
   return true;
}
else if ( ( !(/\./g.test(getTarget(e).value)) ) && (keychar == ".") ) { 
  return true;
}
else
   return false;
}

</script> 
</head>
<body >

<form ID="Form1">
  <input name="number"  onKeyPress="return numbersonly(event)" ID="Text1">
</form>

</body>
</html>

Open in new window

0
 
LVL 20

Expert Comment

by:Proculopsis
ID: 34977581

// Is this any use:

function eventOnKeyUp( caller ) {
  var value = caller.value.replace( /[^\d\.]/g, "" );
  value = value.match( /\d+(\.\d?)?/ );
  value = (value)? value[0] : "";
  if ( caller.value != value ) {
    caller.value = value;
  }
}

<input onkeyup="eventOnKeyUp(this);" />
0
 
LVL 75

Expert Comment

by:käµfm³d 👽
ID: 34979110
Why don't you check onKeyDown and onKeyPress instead of key up?

http://help.dottoro.com/ljlkwans.php
0
U.S. Department of Agriculture and Acronis Access

With the new era of mobile computing, smartphones and tablets, wireless communications and cloud services, the USDA sought to take advantage of a mobilized workforce and the blurring lines between personal and corporate computing resources.

 

Author Comment

by:hibbsusan
ID: 34979156
Hi,

sjklein42: that combination you've used works pretty well in chrome and safari. However, in Firefox, it gives multiple decimals. When I hit the decimal button once, I get a decimal (as I should). When I hit it twice, nothing happens. When I hit it a third time, I get another decimal.

Do you have any idea why this would be? Or a way to fix it?

Thanks so much to you and pratima_mcs!
0
 
LVL 16

Expert Comment

by:sjklein42
ID: 34980299
I'll look into why it isn't working on FF.
0
 
LVL 16

Assisted Solution

by:sjklein42
sjklein42 earned 250 total points
ID: 34980547
Not sure why the regex technique I was using wasn't working reliably on FF, but here's a version that should work well on both IE and FF.  Thanks to pratima_mcs for her excellent foundation.

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.0 Transitional//EN">
<html>
<head>
<title></title>
<meta name="GENERATOR" content="Microsoft Visual Studio .NET 7.1">
<meta name="vs_targetSchema" content="http://schemas.microsoft.com/intellisense/ie5">
<script language=javascript type=text/javascript  >

function getTarget(e) {
	var targ;
	if (!e) var e = window.event;
	if (e.target) targ = e.target;
	else if (e.srcElement) targ = e.srcElement;
	if (targ.nodeType == 3) // defeat Safari bug
		targ = targ.parentNode;
	return targ;
}


function numbersonly(e) {
var key;
var keychar;

if (window.event) {
   key = window.event.keyCode;
}
else if (e) {
   key = e.which;
}
else {
   return true;
}
keychar = String.fromCharCode(key);

if ((key==null) || (key==0) || (key==8) ||  (key==9) || (key==13) || (key==27) ) {
   return true;
}
else if ((("0123456789").indexOf(keychar) > -1)) {
   return true;
}
else if ( ( (getTarget(e).value.indexOf('.')) == (-1) ) && (keychar == ".") ) { 
  return true;
}
else
   return false;
}

</script> 
</head>
<body >

<form ID="Form1">
  <input name="number"  onKeyPress="return numbersonly(event)" ID="Text1">
</form>

</body>
</html>

Open in new window

0
 

Author Comment

by:hibbsusan
ID: 34981301
That's wonderful. Thank you!
0
 
LVL 16

Expert Comment

by:sjklein42
ID: 34981580
Following up on why my first version (using Javascript  regex) didn't work reliably on Firefox:

I just installed the latest Firefox 4.0 Beta 11 version and now the regex works fine.

There must have been a bug in FF.  I haven't tracked it further.

Stick with the final version of our code - it should work fine.  Very useful piece.
0

Featured Post

Is Your Active Directory as Secure as You Think?

More than 75% of all records are compromised because of the loss or theft of a privileged credential. Experts have been exploring Active Directory infrastructure to identify key threats and establish best practices for keeping data safe. Attend this month’s webinar to learn more.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

If your app took Google’s lash recently, here are the 5 most likely reasons.
Developer portfolios can be a bit of an enigma—how do you present yourself to employers without burying them in lines of code?  A modern portfolio is more than just work samples, it’s also a statement of how you work.
This video demonstrates basic masking and how to edit the mask to reveal the desired image.
The viewer will learn how to successfully create a multiboot device using the SARDU utility on Windows 7. Start the SARDU utility: Change the image directory to wherever you store your ISOs, this will prevent you from having 2 copies of an ISO wit…

911 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

18 Experts available now in Live!

Get 1:1 Help Now