Solved

accept only numbers and one decimal

Posted on 2011-02-24
10
974 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
[X]
Welcome to Experts Exchange

Add your voice to the tech community where 5M+ people just like you are talking about what matters.

  • Help others & share knowledge
  • Earn cash & points
  • Learn & ask questions
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
Resolve Critical IT Incidents Fast

If your data, services or processes become compromised, your organization can suffer damage in just minutes and how fast you communicate during a major IT incident is everything. Learn how to immediately identify incidents & best practices to resolve them quickly and effectively.

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

Industry Leaders: 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!

Question has a verified solution.

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

This article discusses how to create an extensible mechanism for linked drop downs.
Invest in your employees with these five simple steps to improve employee engagement and retention.
The viewer will learn how to successfully download and install the SARDU utility on Windows 8, without downloading adware.
The viewer will learn how to successfully download and install the SARDU utility on Windows 7, without downloading adware.

710 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