Number Field Form Helper
I thought I'd like to do something like f.number_field, auto-injecting some javascript onkeypress filter to allow only numbers to be entered into field - so I made it happen.
1) Put this Javascript code in your application.js or other javascript included file:function numbersonly(e){
var unicode=e.charCode? e.charCode : e.keyCode
alert("KeyCode: "+unicode)
if (unicode!=8 && unicode!=9 && unicode!=16 && unicode!=17 && unicode!=35 && unicode!=36 && unicode!=37 && unicode!=39 && unicode!=46 && unicode!=114 && unicode!=116 && unicode!=190 && unicode!=63232 && unicode!=63233 && unicode!=63234 && unicode!=63235 && unicode!=46 && unicode!=63272) { //allow all these keys: 8=backspace; 9=tab; 16=shift; 17=ctrl; 35=end; 36=home; 37=left; 39=right; 190=period; 63232+=safari-arrowkeys;
if (unicode<48||unicode>57) //if not a number
return false //disable key press
}
}
2) Create a file called 'helpers/date_picker_helper.rb' with the following code:module NumberFieldHelper
def color_amount(amount)
amount = 0 if amount.nil?
amount.to_f > 0 ? "#{amount}" : (amount.to_f == 0 ? "#{amount}" : "#{amount}")
end
end
module ActionView
module Helpers
module FormHelper
def number_field(object_name, method, options = {})
InstanceTag.new(object_name, method, self, nil, options.delete(:object)).to_input_field_tag(options.merge({:onkeypress => 'return numbersonly(event)'}))
end
end
module FormTagHelper
def number_field_tag(name, value = nil, options = {})
tag :input, { "type" => "text", "name" => name, "id" => name, "value" => value, "onkeypress" => 'return numbersonly(event)' }.update(options.stringify_keys)
end
end
class FormBuilder
def number_field(method, options = {})
@template.number_field(@object_name, method, options.merge(:object => @object))
end
end
end
end
4) Insert "include NumberFieldHelper" into your ApplicationHelper.
5) Begin using! Sample code, with the two usual formats of FormBuilder:
<% form_for :shape, :url => shape_path(@shape) do |f| -%>
<%= f.number_field(:sides) %>
<%= number_field(Shape, :sides, :value => @shape.sides) %>
<% end -%>
6) Enjoy your numerical limitation in your form fields!
I had some trouble with the keycodes - this was created on a mac, and I think some of them are different than Windows, as well as differing browsers. If you know of another javascript function that will do the same thing (allow only numbers, as well as other navigational keys), post it here! I'm sure something better is out there...