Jump to content

Strict Decimal Input Field


Diegar
 Share

Recommended Posts

Basically, i have an input field in a form, that i want someone to enter in a decimal to. The field needs to be big enough for only 4 characters, '00.0', but needs to place the decimal automatically. So when they type in '042', it will show up right in front of them as '04.2'. Is this easily achieved?

Link to comment
Share on other sites

i am working to it, but what i have to admit is that i really didn't write JS for a long time. So, here's my code. This does NOT work!! But i would like to post it, share, and for discussion. It will be great if it can give some tips to other programmers.

<html><head><script>function decimal(e){  var text = document.getElementById("abc").value;  var input;  if(window.event) // IE	input = e.keyCode;  else if(e.which) // Netscape/Firefox/Opera	input = e.which;  input = String.fromCharCode(input);/*alert("input: "+input);alert("text: "+text);text="123";alert(text.search("."));*/  if (input == '.')				// input a dot	if (text.length)	  return (text.indexOf(".")<0);	 // if there is already a dot, not allow another one	else	  { document.getElementById("abc").value = 0; return true; }  else if (isFinite(input)){	   // input a num	switch (text.length){	  case 0: return true;	  case 2: document.getElementById("abc").value += "."; return true;	}  } else	return false;}</script></head><body><input id="abc" type="text" maxlength="4" onkeypress="return decimal(event)" /></body></html>

And finally, a few words to add. Checking things at client side is absolutely unreliable!! You'd better double check it at the server side, by PHP or ASP or whatever. =)

Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
 Share

×
×
  • Create New...