Go Premium for a chance to win a PS4. Enter to Win

x
?
Solved

accept only numbers and one decimal

Posted on 2011-02-24
10
Medium Priority
?
978 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 1000 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
Technology Partners: We Want Your Opinion!

We value your feedback.

Take our survey and automatically be enter to win anyone of the following:
Yeti Cooler, Amazon eGift Card, and Movie eGift Card!

 
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
 

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 1000 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

Vote for the Most Valuable Expert

It’s time to recognize experts that go above and beyond with helpful solutions and engagement on site. Choose from the top experts in the Hall of Fame or on the right rail of your favorite topic page. Look for the blue “Nominate” button on their profile to vote.

Question has a verified solution.

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

Rules and regulations were devised in order to maintain the integrity of a system. However, interpretation of rules can be quite tricky.
There can be many situations demanding the conversion of Outlook OST files to PST format and as such, there is no shortage of automated tools to perform this conversion. However, what makes Stellar OST to PST converter stand above the rest? Let us e…
In this brief tutorial Pawel from AdRem Software explains how you can quickly find out which services are running on your network, or what are the IP addresses of servers responsible for each service. Software used is freeware NetCrunch Tools (https…
Please read the paragraph below before following the instructions in the video — there are important caveats in the paragraph that I did not mention in the video. If your PaperPort 12 or PaperPort 14 is failing to start, or crashing, or hanging, …

971 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