Sonal S.
Sonal S.

Reputation: 1442

Bind dropdown using jQuery in ruby on rails

I have following form in html.erb file

users.html.erb

 <% form_tag (:action =>:abc_action)do%>
                            <%= label_tag(:user,"Select User") %><br/>
                             <%=collection_select("user",id",@result,"uid","uid",:prompt=>"--Select User--")%><br/>
    <%= collection_select("subject", "id",@res,"id", "id",:prompt=>"--Select Subject--")%><br/>

   <%= submit_tag 'Submit',:id => 'btn'%>
                    <%end %>

I want to change content of second dropdown according to selected value of first dropdown.

For this, I m calling jQuery method on change event of first dropdown. The controller is working properly and value returned by controller is of array type.

My jQuery code is....

jQuery(document).ready(function() {
jQuery("#edetail_id").change(function() {
    jQuery.get('/requests/find_val/?emid=' + jQuery("#user_id").val(),function(data)
   {

          jQuery("#subject_id").html(data);
   }); 
 });
});

My Controller is Users_controller.rb

 def find_val
 @acc = user.find(:all, :conditions => ["uid = ?", params[:emid] ])
     @res = Array.new
                            for result in @acc
                                    @res << result.ndid
                            end

          render :text => @res

 end

Please anyone help me.. How can i do this?

Upvotes: 2

Views: 1097

Answers (1)

Andreas Lyngstad
Andreas Lyngstad

Reputation: 4927

I have to guess a bit, but I think this will push you in the right direction. I really do not like rails select helpers for this kind of things. You might just make regular html selects within a erb loop

<% form_tag (:action =>:abc_action)do%>
     <%= label_tag(:user,"Select User") %><br/>
     <%=collection_select("user","id", @result,"uid","uid",:prompt=>"--Select User--")%>
     <div id="result_holder">
      <%= collection_select("subject", "id",@res,"id", "id",:prompt=>"--Select",    
     :html=> {:id => "result"})%>
     </div>
    <br/>
     <%= submit_tag 'Submit',:id => 'btn'%>
   <%end %>

jQuery

jQuery(document).ready(function(){
jQuery("#edetail_id").change(function() {
    var id =  jQuery("#user_id").val()
    jQuery.get('/requests/find_val/' + id)
});

routes.rb

match "/users/find_val/:id" => "users#find_val", :as => :todo_select

I am guessing that you want the subjects to the selected user

def find_val
 @subjects = User.find(params[:id]).subjects
end

views/users/find_val.js

$("#result_holder").empty().append("<%=j( collection_select("subject", "id",@subjects,"id", "id",:prompt=>"--Select Subject--")%>")

Upvotes: 1

Related Questions