Search code examples
javascriptruby-on-rails-2

pass selected drop down value as params in rails link_to


I have a select tag which populates list of department names, When I select a value from drop down, I need to display an edit link below (link_to) and append the selected value of dropdown as id params.(I am not using form for this single select tag since I dont need to save value in my databse). How this could be possible. Please help. I am using rails2.3

I tried like the below but it didn't work.

  Select A Dept
    <%=select :select_dept, :dept, @dept.map{|dept| [dept.full_name, dept.id]},{:prompt => "#{t('select_a_batch')}"} %>
     <%= link_to "Display", {:controller => "user", :action => "display_value", :id => $('#select_dept').val() } ,:class => "button" %>

Solution

  • Gopal is on the right track.

    Give the link an id so you can pick it out

    <%= link_to 'Display", {:controller ...}, :class => 'button', :id => 'display_link' %>
    

    Hide it with CSS by default

    #display_link { display:none; }
    #display_link.showing { display:block; }
    

    Then in javascript, do something like

    $('#select_dept').on('change', function(ev) {
       var deptId = $(this).find(':selected').val();
       var newPath = '/users/' + deptId + '/display_value';
       $('#display_link').attr('href', newPath);
       $('#display_link').addClass('showing');
    });
    

    This will not set things up on page load, but you could run the same function you've passed as the change callback on page load to set things up (assuming one of the items might be selected on load).