# Automatically populating list box items using Ajax

**URL:** <https://www.ruby-forum.com/t/automatically-populating-list-box-items-using-ajax/109073>\
**Category:** Rails\
**Created:** [July 11, 2007, 10:34am UTC](https://www.ruby-forum.com/t/automatically-populating-list-box-items-using-ajax/109073 "2007-07-11T10:34:35Z")\
**Posts on this page:** 7\
**Page:** 1

<div class="post-metadata">

**Author:** ![unnikrishnanes](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/u/ce73a5/32.png) [@unnikrishnanes](https://www.ruby-forum.com/u/unnikrishnanes)\
**Post date:** [July 11, 2007, 10:34am UTC](https://www.ruby-forum.com/t/automatically-populating-list-box-items-using-ajax/109073/1 "2007-07-11T10:34:35Z")

</div>

I have page where I have 2 list box , one for countries and one for  
states.

and I have tables for country and state.

What I want is when I click on any country name , in the next list box  
it should display all the states in that particular country. I have an  
idea but dont know how to do with Ajax. Would be great if any one can  
come up with some example.

Thanks in advance

---

<div class="post-metadata">

**Author:** ![unnikrishnanes](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/u/ce73a5/32.png) [@unnikrishnanes](https://www.ruby-forum.com/u/unnikrishnanes)\
**Post date:** [July 11, 2007, 10:55am UTC](https://www.ruby-forum.com/t/automatically-populating-list-box-items-using-ajax/109073/2 "2007-07-11T10:55:12Z")

</div>

On Jul 11, 1:34 am, Unni K. [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid)  
wrote:

> Thanks in advance
> 
> –

can you read Portuguese? I can’t

[http://eustaquiorangel.com/blog/show/367](http://eustaquiorangel.com/blog/show/367)  
[http://groups.google.com/group/rubyonrails-talk/browse\_frm/thread/581d86e2a4b359c2?q=drop+down&](http://groups.google.com/group/rubyonrails-talk/browse_frm/thread/581d86e2a4b359c2?q=drop+down&)

---

<div class="post-metadata">

**Author:** ![unnikrishnanes](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/u/ce73a5/32.png) [@unnikrishnanes](https://www.ruby-forum.com/u/unnikrishnanes)\
**Post date:** [July 11, 2007, 11:09am UTC](https://www.ruby-forum.com/t/automatically-populating-list-box-items-using-ajax/109073/3 "2007-07-11T11:09:25Z")

</div>

no, i cant read .

---

<div class="post-metadata">

**Author:** ![unnikrishnanes](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/u/ce73a5/32.png) [@unnikrishnanes](https://www.ruby-forum.com/u/unnikrishnanes)\
**Post date:** [July 11, 2007, 11:13am UTC](https://www.ruby-forum.com/t/automatically-populating-list-box-items-using-ajax/109073/4 "2007-07-11T11:13:19Z")

</div>

> no, i cant read .

Babelfish to the rescue! Good luck reading its output!

Rails: Modifying the OPTIONs of the SELECTs  
Publicado/atualizado in 09/03/2007 12:37  
Yesterday she was giving a hand to the night for my wife, who is to  
webdesigner and is learning to program now, guess, with Rails (and they  
guess who is the support-technician-officer-24-hours-VIP of it, tÃƒÂ´  
ferrado) and yesterday it had one probleminha to fill some SELECTs. I go  
to describe a situation similar to the one that it had:

a… I have 3 SELECTs, one for country, another one for state and  
another one for city;  
b… The logical sequÃƒÂªncia is all there: the country is selected, the  
SELECT of the state is filled, the state is selected, and the cities are  
filled;  
c… I used observe\_field for country and state, indicating the  
corresponding controllers and actions;  
Until there, all good, but probleminhas had appeared ones:

a… I gave a good one searched and I did not find a way to only modify  
the OPTIONs of the SELECT, what the group walks recommending is or to  
use replace\_html and to change to everything of the element where the  
SELECT if finds, (in this in case that I found that the layout went to  
complicate a little) or to use replace to change the proper element, or  
either, to create a new SELECT with this method.  
b… With any one of the options above, observe\_field was maluco. He is  
not for less, we remove and we insert the element that it was  
“watching”, and it stops to look the cities of the state at the moment  
that we remove and we insert the element of state with the values  
returned for the consultation for country.  
I go to try to illustrate a little the problem and the solution with  
code (where I only joined everything in a place only for didactic ends,  
they separate to its controllers certinho). I generated a controller  
general pool with the actions (methods, dÃƒÂ£) states, cities and new, and  
a mount of hashes and arrays to make a simulation of data come of the  
data base.

The play that I made was to use the method call, that called a function  
Javascript in the page that requested call AJAX. This function (nastily  
inserted there inside of the action, for effect of the example - they  
will be to use place it in an archive js) receives id from the SELECT  
that we want to bring up to date and the Array with the data to be  
inserted, makes a “clean one” in the bred new SELECT and adds the  
OPTIONs from the values of the sent Array. The controller is thus:

class GeralController \< ApplicationController  
def estados  
@paises\_estados = {1=\>[[ ’ SP’, 1], [‘mg’, 2]], 2=\>[[‘j1’, 3],  
[‘j2’, 4] ],  
3=\>[[‘C1’, 5], [‘c2’, 6] ]} to relieve:update of |page|  
page.call ’ fill ', ’ states ',  
@paises\_estados[params[:id].to\_i ] page.call ’ fill ', ’ cities ', []  
end end def cities @estados\_cidades = {1=\>[[‘Mirassol’, 1], [‘Rio  
Preto’, 2 ] ], 2=\>[[‘Belo Horizonte’, 3], [‘DivinÃƒÂ³polis’, 4]],  
3=\>[[‘Tokio’, 5] ], 4=\>[[‘Osaka’, 6]], 5=\>[[‘Alberta’, 5]],  
6=\>[[‘Vancouver’, 6] ]} to relieve:update of |page| page.call ’  
fill ', ’ cities ‘,  
@estados\_cidades[params[:id].to\_i ] end end def new @paises = [ [ ’  
Brasil’, 1], [‘JapÃƒÂ£o’, 2], [‘CanadÃƒÂ¡’, 3] ] end end  
There in the controller all time has a play to send an empty Array of  
cities that are returned new states, preventing the inconsistency to be  
with the selected cities previously filled. E view new, already with the  
function fill, is thus:

\< script type=“text/javascript” \> function fill(id,  
val){to var select = $(id); to var length = select.length;  
to for(var i=0; i\<length; i++) select.remove(0);  
if(val.lenght\<=0) return;  
select.appendChild(document.createElement(“option”));  
val.each(function(opt){to var option =  
document.createElement(“option”); option.text = opt[0];  
option.value = opt[1]; select.appendChild(option);  
})} \< form \> \< p \> \< label  
for=“paises”\>PaÃƒ-ses \< select id=“paises” \> \< option\>\</option

> \< % = options\_for\_select(@paises) % \>
> 
> \< p \> \< label  
> for=“estados”\>Estados \< select id=“estados” \> \</p  
> \< p \> \< label for=“cidades”\>Cidades \< select id=“cidades” \>  
> 
> \< p id=“status”\>
> 
> \< % = observe\_field ’ paises  
> ',:url=\>{:action=\>'estados '},:with=\>'id ’ % \> \< % = observe\_field ’  
> states ',:url=\>{:action=\>'cidades '},:with=\>'id ’ % \>   
> I looked for in Prototype and vi much thing not to deal myself with  
> SELECTs, there therefore I made some things half “in the nail” in the  
> function, as to erase the elements and to create the OPTIONs, if  
> somebody to know a direct skill in the Prototype sends me an email that  
> I bring up to date the code. He was very late yesterday and I was not  
> with bag to be fuÃƒÂ§ando excessively in the API of the Prototype not  
> (although to have sufficiently improved, still he is having a search, he  
> has much thing there).

With this solution I prevented to be removing and inserting the SELECT  
that I want popular and preventing any problems related to the this.

–  
Phlip  
[Test Driven Ajax (on Rails) [Book]](http://www.oreilly.com/catalog/9780596510657/)  
“Test Driven Ajax (on Rails)”  
assert\_xpath, assert\_javascript, & assert\_ajax

---

<div class="post-metadata">

**Author:** ![unnikrishnanes](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/u/ce73a5/32.png) [@unnikrishnanes](https://www.ruby-forum.com/u/unnikrishnanes)\
**Post date:** [July 11, 2007, 11:27am UTC](https://www.ruby-forum.com/t/automatically-populating-list-box-items-using-ajax/109073/5 "2007-07-11T11:27:21Z")

</div>

On Jul 11, 2:12 am, “Phlip” [removed\_email\_address@domain.invalid](mailto:removed_email_address@domain.invalid) wrote:

> c… I used observe\_field for country and state, indicating the corresponding controllers and actions;  
> @paises\_estados = {1=\>[[ ’ SP’, 1], [‘mg’, 2]], 2=\>[[‘j1’, 3], [‘j2’, 4] ],  
> \< script type=“text/javascript” \> function fill(id,  
> for=“estados”\>Estados \< select id=“estados” \>
> 
> \< p \> \< label for=“cidades”\>Cidades \< select id=“cidades” \>  
> [Test Driven Ajax (on Rails) [Book]](http://www.oreilly.com/catalog/9780596510657/)  
> “Test Driven Ajax (on Rails)”  
> assert\_xpath, assert\_javascript, & assert\_ajax

Huh, that’s pretty comprehensible, actually. OK, here’s some in  
Ingrish, the only language i can speak/writ

[http://www.sciwerks.com/blog/2006/07/07/updating-select-controls-with-ajax/](http://www.sciwerks.com/blog/2006/07/07/updating-select-controls-with-ajax/)

[http://www.roryhansen.ca/?p=9](http://www.roryhansen.ca/?p=9)

---

<div class="post-metadata">

**Author:** ![unnikrishnanes](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/u/ce73a5/32.png) [@unnikrishnanes](https://www.ruby-forum.com/u/unnikrishnanes)\
**Post date:** [October 15, 2007, 3:07pm UTC](https://www.ruby-forum.com/t/automatically-populating-list-box-items-using-ajax/109073/6 "2007-10-15T15:07:26Z")

</div>

On Wed, 2007-07-11 at 10:34 +0200, Unni K. wrote:

> Thanks in advance

I wrote a JavaScript a few days ago which should work for this:

[http://piano.altipla.no/pages/form\_helper](http://piano.altipla.no/pages/form_helper)

–  
Tore D.  
removed\_email\_address@domain.invalid  
Trondheim, NO  
[http://tore.darell.no/](http://tore.darell.no/)

---

<div class="post-metadata">

**Author:** ![unnikrishnanes](https://www.ruby-forum.com/letter_avatar_proxy/v4/letter/u/ce73a5/32.png) [@unnikrishnanes](https://www.ruby-forum.com/u/unnikrishnanes)\
**Post date:** [October 15, 2007, 1:38pm UTC](https://www.ruby-forum.com/t/automatically-populating-list-box-items-using-ajax/109073/7 "2007-10-15T13:38:06Z")

</div>

> Huh, that’s pretty comprehensible, actually.

I need to make some English versions of some posts. 🙂
