0

I'm working with a web page containing a form with a textarea element. I want to restrict the input values to only numbers, using JavaScript. One method I have found is to check the keyvalues when users are entering data:

function checkForEnter() {
if (!((event.keyCode >= 48) || (event.keyCode <= 57))) {                            
//event.stopPropagation(); throw error with IE ver 8
event.cancelBubble = true;
event.returnValue = false;
return false;
                    
  }
}

What other method could I use to restrict the values entered?

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
Leonidas
  • 21
  • 1
  • 4
  • Check this [post](http://stackoverflow.com/questions/7454591/allow-only-numeric-value-in-textbox-using-javascript) out – Stokedout Jan 04 '13 at 16:11

3 Answers3

1

Thanks for your help

this solution works for me

The inputext has attach two events to the same function(checkForEnter ) , onkeypress and onkeydown

both cases I validate ONLY numbers

no more bla , bla bla,

function checkForEnter() { 
if (event.keyCode == 13) {

var txt = event.srcElement;      

                    }
//that was my problem
//var chCode = ('charCode' in event) ? event.which : event.keyCode;

//that was my solution
var chCode = event.keyCode; 


                    if (chCode != 8 || chCode != 46) {

//alphanumeric keyboard
                        if (chCode >= 48) {
                            if (chCode <= 57) {
                            }
                            else {
//numeric keyboard
if (chCode > 95 && chCode < 106) {
                                } else {
                                    event.cancelBubble = true;
                                    event.returnValue = false;
                                    return false;
                                }
                            }
                        }
if (chCode == 32) {
   event.cancelBubble = true;
event.returnValue = false;
return false;
}        
}                                      
}

ps. I cannot

I can not make multiple comparisons in javascript

: (

for that reason use if .. if .. if

Leonidas
  • 21
  • 1
  • 4
0

You want event.preventDefault(), not event.stopPropagation(). preventDefault stops the default behavior of the key press event (i.e., adding a character into the text field).

apsillers
  • 112,806
  • 17
  • 235
  • 239
0

Your function is missing an event parameter, so invoking methods of an undefined variable naturally results in an error. Try:

function checkForEnter(event) {
    ...
}
Asad Saeeduddin
  • 46,193
  • 6
  • 90
  • 139
  • I assume the OP is using `attachEvent` in IE-specific code, which uses a global `event` property. That said, this is still a good suggestion for cross-browser support. – apsillers Jan 05 '13 at 01:40