Smudly Posted April 12, 2011 Share Posted April 12, 2011 I'm working on only allowing numbers & decimals into text fields. So far, I have it deleting Letters, but it really should never allow letters to be typed in in the first place. It is also deleting decimal points, which is not what I need it to do. How do I prevent typing in letters altogether using this code? see example page here: click here The top field is the one we're working with right now. Here is a snippet of my code: creditsBanner = parseFloat(document.convertform.creditsbanner.value); creditsBalance = "<?php echo $creditsBalance;?>"; if (!isNaN(creditsBanner)) { if(creditsBanner>creditsBalance){ document.convertform.creditsbanner.value = creditsBalance; creditsBanner = creditsBalance; } document.convertform.creditsbanner.value = creditsBanner; } else{ alert ("Only numbers are allowed in this field"); document.convertform.creditsbanner.value = ""; } Link to comment https://forums.phpfreaks.com/topic/233508-only-allowing-numbers-and-decimals/ Share on other sites More sharing options...
.josh Posted April 12, 2011 Share Posted April 12, 2011 <form name='convertform' action='..' method='..'> <input type='text' name='creditsbanner' onkeypress='return validateField(event)'> </form> <script type='text/javascript'> function validateField(e) { return !(/[^0-9.]/.test(String.fromCharCode((window.event)?e.keyCode:e.which))); } </script> Link to comment https://forums.phpfreaks.com/topic/233508-only-allowing-numbers-and-decimals/#findComment-1200779 Share on other sites More sharing options...
Smudly Posted April 12, 2011 Author Share Posted April 12, 2011 I was told using charCode is a bad idea and isNaN is more efficient. Is this true? EDIT: Also, using your function doesn't allow users to backspace, delete or move the cursor left or right using the arrows. Link to comment https://forums.phpfreaks.com/topic/233508-only-allowing-numbers-and-decimals/#findComment-1200804 Share on other sites More sharing options...
Recommended Posts
Archived
This topic is now archived and is closed to further replies.