Forum: Ruby on Rails change event in one combo box to update another combo box

Announcement (2017-05-07): www.ruby-forum.com is now read-only since I unfortunately do not have the time to support and maintain the forum any more. Please see rubyonrails.org/community and ruby-lang.org/en/community for other Rails- und Ruby-related community platforms.
Cdcdda30ac4e349c6ffd0819b9e1666f?d=identicon&s=25 Jay Pangmi (jaeezzy)
on 2008-10-05 12:14
Hi, I have two combo boxes. One combo box has the name of countries
stored in the database. So, when a country is selected from this combo
box I want other combo box to list all the cities stored in the database
related to that selected country without clicking any button. Any help
would be great.. thanks
Fb83976abd4d2d2f5f4c4f086a3b09f6?d=identicon&s=25 Raja Venkataraman (rajasaur)
on 2008-10-05 14:06
Jay Pangmi wrote:
> Hi, I have two combo boxes. One combo box has the name of countries
> stored in the database. So, when a country is selected from this combo
> box I want other combo box to list all the cities stored in the database
> related to that selected country without clicking any button. Any help
> would be great.. thanks

There are 2 ways to do it.
a) Have a onChange listener on your country Select control which submits
back to your action_controller and repopulate the form,

b) Make an AJAX call using remote_function method. Take a look at
http://www.railsbrain.com/api/rails-2.1.0/doc/inde...
for an example.
Cdcdda30ac4e349c6ffd0819b9e1666f?d=identicon&s=25 Jay Pangmi (jaeezzy)
on 2008-10-05 16:08
Raja Venkataraman wrote:
> Jay Pangmi wrote:
>> Hi, I have two combo boxes. One combo box has the name of countries
>> stored in the database. So, when a country is selected from this combo
>> box I want other combo box to list all the cities stored in the database
>> related to that selected country without clicking any button. Any help
>> would be great.. thanks
>
> There are 2 ways to do it.
> a) Have a onChange listener on your country Select control which submits
> back to your action_controller and repopulate the form,
>
> b) Make an AJAX call using remote_function method. Take a look at
> http://www.railsbrain.com/api/rails-2.1.0/doc/inde...
> for an example.

Thank for the reply but me being new and bit dumb couldn't make use of
it. I searched for the onChange listener in Rails but couldn't find.
Also I couldn't figure out how I can use the remote_function that you
suggested. I have made my one combo box as:
<form>
  <%=select("selected","location",GreatWalk.getAvailableLocations)%)
</form>

In the controller:
def self.getAvailableLocations
 @locations=GreatWalk.find(:all)
 @locationhoder=[]
 for locs in @locations
  @locationholder<<[locs.location,locs.location]
 end
 @locationholder
end

So, plz guide me thru... thnx.
Cdcdda30ac4e349c6ffd0819b9e1666f?d=identicon&s=25 Jay Pangmi (jaeezzy)
on 2008-10-05 16:10
Jay Pangmi wrote:

> In the controller:
> def self.getAvailableLocations
>  @locations=GreatWalk.find(:all)
>  @locationhoder=[]
>  for locs in @locations
>   @locationholder<<[locs.location,locs.location]
>  end
>  @locationholder
> end
>
> So, plz guide me thru... thnx.

sorry I mean in the model here... thnx
Cdcdda30ac4e349c6ffd0819b9e1666f?d=identicon&s=25 Jay Pangmi (jaeezzy)
on 2008-10-06 08:23
Thanks, I somehow got it fixed using observe_field. But, I'm not sure if
its the right way in the scenario which is like: One combo box with name
of location is on the top and when ever I change the location the combo
box underneath will be updated with the areas within the location
selected in the top combo box. With this bottom combo box there are few
other text boxes as well where some input is given. At the bottom is a
button "proceed to next area" when clicking which a new combo box with
the similar text fields gonna add to the bottom of that updated combo
box with the next area name. This keeps on until the end of the list is
reached. Ok this is similar to what I'm trying to make:

https://www.epa.qld.gov.au/parks/iaparks/gds/IAGDS450.jsp

Here's how got the first part sorted which is updating bottom combo with
the top combo:

IN CONTROLLER:
--------------------------------------------------------------------------------
class UserController < ApplicationController
  def index
  end
  def update_campsites
    @campholder=[]
    id=params["walk_id"]
    @camps=Campsite.find_by_sql("select camp_location from campsites
where walk_id="+id)
    for eachcamp in @camps
      @campholder << [eachcamp.camp_location, eachcamp.camp_location]
    end
  end
end
--------------------------------------------------------------------------------

IN MODEL: (loads great walks locations)
--------------------------------------------------------------------------------
class GreatWalk < ActiveRecord::Base
  def self.getAvailableLocations
    @locations=GreatWalk.find(:all)
    @locationsholder=[]
    for eachlocation in @locations
      @locationsholder << [eachlocation.location,eachlocation.id]
    end
    @locationsholder
  end
end
--------------------------------------------------------------------------------

IN MODEL: (loads campsite locations)
--------------------------------------------------------------------------------
class Campsite < ActiveRecord::Base
  belongs_to :great_walk
  belongs_to :fee
  has_many :customer_bookings
  def self.getAvailableCamps
    @campsholder=[]
    @camps=Campsite.find(:all)
    for camp in @camps
      @campsholder << [camp.camp_location, camp.id]
    end
    @campsholder
  end
end
--------------------------------------------------------------------------------

IN VIEW: (index.rhtml)
--------------------------------------------------------------------------------
<h1>Great Walks Online Booking</h1>
<form>
  <%= select(:selected, :id, GreatWalk.getAvailableLocations, {:prompt
=> 'Select a category'}, :id => :id_selected) %>

  <%= observe_field :id_selected, :url => {:action =>
:update_campsites}, :update => :campsites, :with => "walk_id" %>
</form>
<div id="campsites">
  <form>
    <%=select "selected","camp","Please select location first:"%>
  </form>
</div>
--------------------------------------------------------------------------------

IN VIEW: (update_campsites.rhtml)
--------------------------------------------------------------------------------
<%form_tag do %>
    <p>
      <label for="camp location">Campgroud</label>
      <%=select "selected","camp",@campholder%>
    </p>
    <p>
      <label for="arrival date">Arrival Date</label>
      <%=text_field_tag :name, params[:name]%>
    </p>
    <p>
      <label for="nights">Nights</label>
      <%=text_field_tag :nights, params[:nights]%>
    </p>
    <p>
      <label for="parents">Parents</label>
      <%=text_field_tag :parents, params[:parents]%>
    </p>
    <p>
      <label for="children">Children</label>
      <%=text_field_tag :children, params[:children]%>
    </p>
    <%=submit_tag "Calculate"%>
<%end%>
--------------------------------------------------------------------------------

PLZ any ideas on how can I achieve similar... thanks.
8d4943fb88f56975ec82a14f4a14f77d?d=identicon&s=25 saideep a.v.s (Guest)
on 2008-10-07 10:44
(Received via mailing list)
Hello ,
 Use an Observe_field , so that you can have the country selected as a
parameter and with the help of the country name u can extract the
respective
cities from the database

The following is the code snippet I have used. Might be of some help to
u.

My View Code:
----------------------

<%= form_remote_tag(:update =>"update_div", :url => { :action =>
:register}
) %>
      <p>
        <label for = "country">Country</label> <br />
        <%= select_tag id="user_country",
country_options_for_select(selected = nil,
          priority_countries = ["Select One", "India", "USA",
"Pakistan",
"Nepal", "China"])  %>
       </p>
      <%= observe_field("user_country", :url => { :controller =>
"login",
:action => "check_state"}, :update => "update_list", :with =>
"country")%>

       <div id ="update_list" >
        <p>
          <label for = "state">State</label> <br />
           <%= select("user",:state, %w{ -- }, :class => "select_state")
%>
        </p>
       </div>
</form>

Controller Code:
----------------------------
def check_state
    @result = Country.find(:all, :conditions => [ "country = ?",
params[:country] ] )
    render :partial => 'states', :layout => false
  end


My Partial Code: (To update the states combo box div)
------------------------------------------------------------------------------
<%= stylesheet_link_tag 'css_type1.css' %>
  <p>
    <label for="state">State </label>
    <br/>
   <%= select_tag(id= "user_state",
options_from_collection_for_select(@result,"state", "state"))  %>
  </p>







Thanks & Regards,

Saideep Annadatha


On Sun, Oct 5, 2008 at 3:44 PM, Jay Pangmi
<rails-mailing-list@andreas-s.net
Cdcdda30ac4e349c6ffd0819b9e1666f?d=identicon&s=25 Jay Pangmi (jaeezzy)
on 2008-10-08 02:21
saideep a.v.s wrote:
> Hello ,
>  Use an Observe_field , so that you can have the country selected as a
> parameter and with the help of the country name u can extract the
> respective
> cities from the database

> Thanks & Regards,
>
> Saideep Annadatha

Thanks a tonn saideep for your time and your help. It works great now
but 1 confusion, actually there are many..lol

1) the :with key in the observe_field, what does it takes and its use?
Suppose I got combobox displaying camp_location column from the table
and values as it primary key wich is id. Here :with key takes the value
of the selected location?

2) I gave :with=>"id" and in the controller, I tried:
Campsites.find(:all, :condition=>["walk_id = ?",params["id"]]) but
didn't work but using Campsites.find_by_sql("select * from campsites
where walk_id = "+params["id"]) did the work. I wonder why?

3) Does it matter to do "id" or :id. For example
....:update=>:campsites.... <div id = "campsites"> and vice-versa.

4) observe_field, does it use AJAX? coz it only updates the certain area
of the page and if it does, don't I have to insert
<%=javascript_include_tag :defaults%>

Thanks..
regards,
jay
Cdcdda30ac4e349c6ffd0819b9e1666f?d=identicon&s=25 Jay Pangmi (jaeezzy)
on 2008-10-08 02:27
SORRY I FORGOT TO ASK THIS WHICH IS MORE CONFUSING... why is this
updating working only in the aptana browser (I'm using aptana studio for
rails) and not in IE and FireFox. I checked the javascript is enabled.
Is there something else I need to do?
thanks guys, this place has really been great for me to learn rails..
8d4943fb88f56975ec82a14f4a14f77d?d=identicon&s=25 saideep a.v.s (Guest)
on 2008-10-11 12:20
(Received via mailing list)
Hello Jay,

Sorry for the delay..!!!!
The answers to your doubts are based to best of my knowledge and request
whoever to correct me where found wrong ( me too being new to rails ;) )

1) the :with key in the observe_field, what does it takes and its use?
Suppose I got combobox displaying camp_location column from the table
and values as it primary key wich is id. Here :with key takes the value
of the selected location?

The :with key passes the value you specify there as parameters to the
controller. and by default the :with key takes the value of the observed
field when changed. yeah the :key in ur case must take the selected
location
in the combo box unless if u didnt assign any other value to the :with.


2) I gave :with=>"id" and in the controller, I tried:
Campsites.find(:all, :condition=>["walk_id = ?",params["id"]]) but
didn't work but using Campsites.find_by_sql("select * from campsites
where walk_id = "+params["id"]) did the work. I wonder why?

I have made use of the below statment and it worked fine with me
@result = Country.find(:all, :conditions => [ "country = ?",
params[:country] ] )

if u dont mind my silly doubt. why once try as params[:id] instead of
params["id"] ... but doesnt make any difference though


3) Generally what I have learned was with " " you can have more stack
level
depth traversal than :  ( I too couldn't research more into this and
request
for good place to refer)

4) Yes, it makes Ajax requests in the back.

ANd the browser related question. It worked for me both in IE and
Firefox.
and it completely depends on how you have coded and updated . so I
suggest
to use firebug in firefox so that u can actually know which div is
getting
activated and whats happening and all.


Thanks & Regards,

Saideep Annadatha


On Wed, Oct 8, 2008 at 5:51 AM, Jay Pangmi
<rails-mailing-list@andreas-s.net
F9bdba6e1c8a28664e99e9c8caaa05bd?d=identicon&s=25 Ami (Guest)
on 2008-10-22 05:23
(Received via mailing list)
an excellent tutorial by Ryan biggs: Updating a select box based on
another

http://frozenplague.net/?m=200805 pay attention the observe_field must
have :update => the id on the page you want it to populate
;-)A

On Oct 7, 8:21 pm, Jay Pangmi <rails-mailing-l...@andreas-s.net>
Cdcdda30ac4e349c6ffd0819b9e1666f?d=identicon&s=25 Jay Pangmi (jaeezzy)
on 2008-10-22 13:52
Ami wrote:
> an excellent tutorial by Ryan biggs: Updating a select box based on
> another
>
> http://frozenplague.net/?m=200805 pay attention the observe_field must
> have :update => the id on the page you want it to populate
> ;-)A
>
> On Oct 7, 8:21�pm, Jay Pangmi <rails-mailing-l...@andreas-s.net>

Thank for this info. I will be reading it hard but before that I got one
combo box update another combo using observe_field but only in Aptana
studio browser and when I tried in firefox I get this line with error
while loading the same page and doesn't work. Here's that line but
according to rails api doc I think it should create similar html tag
isn't it?:

<script type="text/javascript">
45//<![CDATA[
46new Form.Element.EventObserver('walks_id', function(element, value)
{new Ajax.Updater('campsites_list', '/user/update_campsites',
{asynchronous:true, evalScripts:true, parameters:'id=' + value +
'&authenticity_token=' +
encodeURIComponent('834004033f4404c8c5a6116d048eeab7e72d7c14')})})
47//]]>
48</script>

The code I'm using in the view that has observe_field is:

================================================================================
<%=javascript_include_tag "prototype"%>

<label for = "walk location">*Locations:</label><br />
<%= select(:walks, :id, Greatwalk.find_available_locations,
          {:prompt=>'Select Great Walk Location'}, :selected => nil) %>
<%= observe_field("walks_id", :url => {:controller => "user", :action =>
"update_campsites"},
               :update => "campsites_list", :with => "id")%>
<div>
<%=error_messages_for 'carts'%>
<%form_tag :action => :add_to_cart do%>
  <table>
    <tr>
      <td>
        <div id ="campsites_list" >
             <label for = "camp location">*Campgrounds:</label><br />
             <%= select_tag "campsite", %w{ ------- }, :class =>
"select_campsites" %>
        </div>
      </td>

 ....................
                </tr>
                <%=submit_tag "Add to cart"%>
        </table>
<%end%>
================================================================================

Thanks..
This topic is locked and can not be replied to.