Often you want to format your number inputs in a pretty and proper way for your users. Using Bootstrap and SimpleForm within your Rails application is a good way to start, but how will you deal with number formatting within your input field for decimal and thousands separators?
autoNumeric.js is an awesome jQuery plugin which solves almost all of your number formatting struggles. This blog post will show you how you can use autoNumeric in combination with Bootstrap and SimpleForm to easily get your number input formatting done. Bootstrap, SimpleForm and jQuery will be a prerequisite of your Rails application.
- To use autoNumeric in your Rails application, please follow the installation guideline at https://github.com/randoum/autonumeric-rails
- Next, we want to create our custom Currency input type within SimpleForm, so that we can use it within our forms. The currency input type will show an € sign in front of the field and it will automatically format the input while typing. To do so, create a new folder
app/inputs
and add the filecurrency_input.rb
. Add the following code:class CurrencyInput < SimpleForm::Inputs::StringInput def input(wrapper_options) input_options = input_html_options.merge({data: {autonumeric: true}}) merged_input_options = merge_wrapper_options(input_options, wrapper_options) template.content_tag(:div, class: 'input-group') do template.concat span_currency_sign template.concat @builder.text_field(attribute_name, merged_input_options) end end def span_currency_sign template.content_tag(:span, class: 'input-group-addon') do template.concat '€'.html_safe end end end
This code adds the
autonumeric
data option to your input field and also adds the € sign within an HTML span in front of your input field. By using the classinput-group
, Bootstrap will render the input field in a proper way and on a single line. - Restart your server.
- Head over to your view file which holds your form (by utilizing the
simple_form_for
helper) and add the following line:= f.input :acquisition_cost, as: :currency
- Thats it! Open your form and you will see a nicely formatted input field with a leading € sign and your input will be augmented with decimal and thousands separators while typing.