Make text field accepts only numeric values

Hello people

I need your help again.

What I want to do is make a text field accepts only numeric values... Thant's means if I press a letter or a simbol the text field should not be filled, it should be just if I press a number.

Is there a rails way (rails 3.0.9) to achieve this issue?

Thanks

I don’t know if there’s a Rails way (I’m still learning it myself) but if you want to implement this on the client you’ll need JavaScript. Or, you can use the HTML5 input type “number”, but that’s not guaranteed to work on all browsers.

http://www.html5tutorial.info/html5-number.php

I would go ahead and code the input type="number" element from HTML5, then provide a fallback for visitors whose browsers don't understand that element. Here's a Prototype.js solution, modify if needed to jQuery depending on your environment:

//include prototype.js before this point document.observe('dom:loaded', function(){   var test = new Element('input',{type:'number'});   if(test.type != 'number'){     $$('input[type="number"]').each(function(elm){       elm.observe('blur',function(evt){         this.setValue($F(this).gsub(/[^0-9]+/,'');     });   } });

Note that if you have a lot of number fields on the same page, this will suck memory, because it defines a callback listener on each field separately. Take a look at the rails.js code for an example of how to force form fields to "bubble" (they don't, usually, not in most browsers) so that you can define a single listener function on the blur event and work out backward whether the field that threw that event needs this filter or not. That will scale much better than this technique, but it's more opaque to look at as an example.

Walter

I'm not sure but it seems to be what you need

Or you could add the html5 option when you write your code

Javier Q

Typo, left out a trailing parenthesis:

//include prototype.js before this point document.observe('dom:loaded', function(){ var test = new Element('input',{type:'number'}); if(test.type != 'number'){    $$('input[type="number"]').each(function(elm){      elm.observe('blur',function(evt){        this.setValue($F(this).gsub(/[^0-9]+/,''));    }); } });

Walter