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 that 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 for your Rails application.
To use autoNumeric in your Rails application, please follow its installation guideline. 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 file
currency_input.rb. Add the following code:
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 class
input-group, Bootstrap will render the input field in a proper way and on a single line.
Now, 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: :currencyThat’s 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 separator while typing.