I was playing around with Ruby on Rails (RoR) over the weekend and I wanted to populate some textfield on the form base on a certain dropdown list selection. After a couple of hours of research, I managed to piece together how it will work in RoR and I decided to share it here for everyone else who are hunting for the information.
Assuming you have a form, with a dropdownlist and 2 textfields with the selection of the dropdownlist you are going to populate the textfields with the corresponding values.
Step 1: Finding out the ID for the forms elements.
I will ask you to view source on your page and take note of the respective elements. In my case they are as follows:
- Dropdownlist : counter_cid
- Textfield 1 : price_input
- Textfield 2 : date_input
Step 2: Using Ajax & Jquery
Add the following into your View page.
In the script, I basically say on the dropdownlist on change, I will call Ajax to the following URL (i will get to this in Step 4) and the data is the value of the dropdownlist selected. Finally, I tell it that this is a script return type.
<% content_for :bodyJS do %>
<% end %>
Step 3: Adding the Method to your Controller file
In your controller file, my case CounterController.rb, insert the following:
This will tell the controller to response to the following format, add this line as the first line in the controller class.
Second, we going to define the method.
name = Counter.find(params[:id]).name
quote = StockQuote::Stock.quote(name)
@currentprice = quote.bid
Step 4: Routes.rb
Now we need to configure the routes so that the ajax call could access.
Change your routes to the following:
resources :counters do
After you are done, do a
rake routes in your terminal to verfiy that is created.
Step 5: Finally adding in the js.erb file.
This will help us update the value back to the texfield
Browse to the counter folder under App-> Views -> Counter -> Add a new file “currentprice.js.erb”
$("#price_Input").val(<%= @currentprice %>);
Finally you are good to go!