Solved

accept only numbers and one decimal

Posted on 2011-02-24
10
966 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
Comment Utility
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
Comment Utility
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
Comment Utility
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
Comment Utility

// 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 74

Expert Comment

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

http://help.dottoro.com/ljlkwans.php
0
Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

 

Author Comment

by:hibbsusan
Comment Utility
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
Comment Utility
I'll look into why it isn't working on FF.
0
 
LVL 16

Assisted Solution

by:sjklein42
sjklein42 earned 250 total points
Comment Utility
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
Comment Utility
That's wonderful. Thank you!
0
 
LVL 16

Expert Comment

by:sjklein42
Comment Utility
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

Better Security Awareness With Threat Intelligence

See how one of the leading financial services organizations uses Recorded Future as part of a holistic threat intelligence program to promote security awareness and proactively and efficiently identify threats.

Join & Write a Comment

A high-level exploration of how our ever-increasing access to information has changed the way we do our jobs.
JavaScript can be used in a browser to change parts of a webpage dynamically. It begins with the following pattern: If condition W is true, do thing X to target Y after event Z. Below are some tips and tricks to help you get started with JavaScript …
The viewer will learn common shortcuts with easy ways to remember them. The viewer will then learn where to find all of the keyboard shortcuts, how to create/change them, and how to speed up their workflow.
Video by: Tony
This video teaches viewers how to export a project from Adobe Premiere Pro and the various file types involved.

763 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

11 Experts available now in Live!

Get 1:1 Help Now