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?
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.
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.
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?
I’m not sure but it seems to be what you need
Or you could add the html5 option when you write your code
//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
This forum is not affiliated to the Ruby language, Ruby on Rails framework, nor any Ruby applications discussed here.