Auto populate form fields from select box selection using RJS

I have a form that I want to auto populate the fields depending on the user selection. This can be achieved using javascript, however as I am digging RAILS, i would like to know how to do it using RJS.

On my view:

<p>Company Name<br/>

<%= select 'field','company_name',CompanyList.find_all.collect {|p| [ p.company_name, p.id ] }, { :prompt => true },
{ :onchange => remote_function(:url => {:action => :get_company_info},:with => "'company_id='+value"),:style => "width:400px;"} %><br/>
<%= text_field "company", "company_name", :size => 50  %>

<small><i><font color="#E9323C">*</font></i></small></p>

<p><b>Company Address</b></p>
<p>Blk/Apt No.<br/>
<%= text_field "company", "address_1", :size => 50  %>
<small><i><font color="#E9323C">*</font></i></small></p>
<p>Street/Unit No.<br/>
<%= text_field "company", "address_2", :size => 50  %>
<small><i><font color="#E9323C">*</font></i></small></p>
<p>Postal Code<br/>
<%= text_field "company", "postal_code", :size => 50  %>
<small><i><font color="#E9323C">*</font></i></small></p>
<p>Country<br/>
<%= country_select 'company', 'country',["Singapore"] %>
<small><i><font color="#E9323C">*</font></i></small></p>

as you see I would let the user select the company name and I would like to populate the rest of the fields.

Here’s what i did on my controller:

  def get_company_info #populate form for company info
         @CompanyList = CompanyList.find(params[:company_id])
         @address1 = (@CompanyList.address_1.nil?) ? '' : @CompanyList.address_1
         @address2 = (@CompanyList.address_2.nil?) ? '' : @CompanyList.address_2
         @postalcode = (@CompanyList.postal_code.nil?) ? '' : @CompanyList.postal_code
          render :update do |page|
            page << "$('company_company_name').value='" + @CompanyList.company_name.titlecase + "';"
            page << "$('company_address_1').value='" + @address1 + "';"
            page << "$('company_address_2').value='" + @address2 + "';"
            page << "$('company_postal_code').value='" + @postalcode + "';"
          end
  end

I achieved that using page rendering using the ‘<<’ to update the DOM element value. Also i need to check whether the string is nil, as when i got a nil it always shows RJS error, so i need to set it to empty string….

Tags: ,
RUBY + RAILS |

If you enjoyed this post, please consider to leave a comment or subscribe to the feed and get future articles delivered to your feed reader.

Comments

No comments yet.

Sorry, the comment form is closed at this time.