pass selected drop down value as params in rails link_to - javascript

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" %>

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).

Related

Cocoon data-association-insertion-node with a function

According https://github.com/nathanvda/cocoon#link_to_add_association you should be able to pass a function to data-association-insertion-node
I have tried this:
<%= link_to_add_association 'Add Timeslot', f, :timeslots, :data => {'association-insertion-node' => 'get_row()'} %>
And this:
<%= link_to_add_association 'Add Timeslot', f, :timeslots, :data => {'association-insertion-node' => 'get_row'} %>
And this (getting desperate):
<%= link_to_add_association 'Add Timeslot', f, :timeslots, :data => {'association-insertion-node' => 'function get_row(node){var row = "<tr></tr>";$("#table_body").append(row);return row;}'} %>
But none of them work.
Javascript:
function get_row(node){
var row = "<tr></tr>"
$("#table_body").append(row);
return row
}
I am trying to add a tr to a table and then append the nested timeslot form to the tr.
At the moment this is not possible what you are trying to do. When setting the data-association-insertion-method like this, it will just be a string in javascript, and not a reference to a method.
As documented in the README, you have to do the following (assuming you gave your links a class .add-timeslot):
$(document).on('turbolinks:load', function() {
$(".add-timeslot a").
data("association-insertion-method", 'append').
data("association-insertion-node", function(link){
return link.closest('.row').next('.row').find('.sub_tasks_form')
});
});
(the example is almost verbatim copied from documention for demonstration purposes only --you will have to fill in your get_row function)

how to make collection_select value as link_to variable

I have the ff:
app/views/reports/index.html.erb
<h1>Reports</h1>
<br>
<legend>Categories</legend>
<div class="row">
<div class="span5">
<ol>
<li><%= link_to 'COMMENDATION', commendations_path(format: 'pdf'), { id: 'commendations_click' } %></li>
<%= collection_select(nil,
:employee_id,
#employees,
:id,
:last_name,
{:prompt => "Select an Employee"},
{:id => 'employees_select'}) %>
<br>
<%= collection_select(nil,
:employee_movement_id,
#employeemovements,
:id,
:position,
{:prompt => "-"},
{:id => 'employee_movements_select'}) %>
<li><%= link_to 'REPORT2', '#' %></li>
<li><%= link_to 'REPORT3', '#' %></li>
</ol>
</div>
</div>
<script type="text/javascript">
$(document).ready(function() {
$('#employees_select').change(function() {
$.ajax({
url: "<%= update_employee_movements_path %>",
data: { employee_id : $('#employees_select').val() },
dataType: "script"
});
});
$('#commendations_click').click(function() {
$.ajax({
url: "<%= commendations_path %>",
data: {
employee_id : $('#employees_select').val(),
employee_movement_id : $('#employee_movements_select').val()
},
dataType: "script"
});
});
});
</script>
app/controllers/reports_controller
class ReportsController < ApplicationController
before_filter :authenticate_user!
# GET /reports
def index
#employees = Employee.all
#employeemovements = EmployeeMovement.distinct_positions
end
def update_employee_movements
if params[:employee_id]
#employeemovements = [].insert(0, "Select Employee Movement")
else
employee = Employee.find(params[:employee_id])
#employeemovements = employee.employee_movements.map{ |a| [a.position, a.id] }.insert(0, "Select Employee Movement")
end
end
def commendations
emdates = EmployeeMovement.last_2_dates_obtained(params[:employee_movement_id])
date_from = emdates[0].date_obtained
date_to = emdates.length == 1 ? nil : emdates[1].date_obtained
emp = Employee.find(params[:employee_id])
#commendations = case date_to.nil?
when true then emp.commendations.this_day_onwards(date_from)
else emp.commendations.within(date_from, date_to)
end
end
end
What I'm trying to do here is, I'm creating a page filled with links and drop down lists that will serve as a Reports center. The idea is, each link will be catered by a controller. Each controller will be responsible in showing my PDF in the browser (through ThinReports, if you're curious).
The #employees_select change event is used for changing the value of the #employee_movements_select collection_select.
Now my problem is, how can i capture the value of both #employees_select and #employee_movements_select and pass them to my commendations action?
I tested link_to by hardcoding values, and it works (code below)
<%= link_to 'COMMENDATION', commendations_path(employee_id: 1, employee_movement_id: 12, format: 'pdf') %>
However, If I use javascript to push the values to my commendations action through the 'click' event, my commendations action will be called twice, thus an error occurs because the params[:employee_id] in the action is now blank.
By the way, I need those values because my commendations action needs it so I can populate my PDF report template.
Please help. Thanks a lot in advance!
UPDATE 1
-> Updated link_to:
<%= link_to 'COMMENDATION', '#', { id: 'commendations_click' } %>
-> Removed dataType: "script" in #commendations_click event handler
-> Updated url: in #commendations_click event handler
url: <%= commendations_path(format: 'pdf') %>
UPDATE 2 (RESOLUTION)
I tweaked my javascript to look something like this:
$('#commendations_click').click(function() {
event.preventdefault();
window.location = "<%=j commendations_path(format: 'pdf') %>" + "?employee_id=" + $('#employees_select').val() + "&employee_movement_id=" + $('#employee_movements_select').val();
});
Works perfect now.
Two things come to mind. You can wrap the two select lists within a form element and just do a submit. Everything inside the form will be submitted to your server and you can process the request and handle the redirect on the server side. The other thing you can do is to handle the commendations click event on the client side using jquery or something. Just bind to the click event of that link, grab the values of the two select lists and do whatever you want with it. Remember, link_to just gets rendered as plain old html links on the view. For e.g.
link_to "Profile", profile_path(#profile) gets rendered as Profile

Can't find the error in my dependent select drop down on Active Admin( Rails 3.2, Active Admin 1.0)

I'm trying to build a RoR app, with three models:
Games that can be classified in a Sector(called GameSector) and in a subsector (called GameSubsector)
A sector is made up of many subsectors.
a Subsector.
Here are my basic models relationships:
models/game.rb
belongs_to :game_sector, :foreign_key => 'game_sector_id', :counter_cache => true
belongs_to :game_subsector, :foreign_key => 'game_subsector_id',:counter_cache => true
I use Active Admin to input the Games, Sectors or subsectors information.
I have a very basic form when I create a game and I'd just like to make the second select drop down (game_subsector) adjust on the choice of the first select (gamesector) so that I don't the the whole (very long) list of game_subsectors but only those that belong to the game_sector I choose.
After dozens of tests and techniques tried but failing, I've finally used this dev's advice that appeared relevant to me: http://samuelmullen.com/2011/02/dynamic-dropdowns-with-rails-jquery-and-ajax/.
But it still does not work.
Here is the form on Active Admin which is located on admin/game.rb
ActiveAdmin.register Game do
menu :parent => "Campaigns", :priority => 1
controller do
with_role :admin_user
def game_subsectors_by_game_sector
if params[:id].present?
#game_subsectors = GameSector.find(params[:id]).game_subsectors
else
#game_subsectors = []
end
respond_to do |format|
format.js
end
end
end
form do |f|
f.inputs "Details" do
f.input :name
f.input :game_sector_id,
:label => "Select industry:",
:as => :select, :collection => GameSector.all(:order => :name),
:input_html => { :rel => "/game_sectors/game_subsectors_by_game_sector" }
f.input :game_subsector_id, :as => :select, :collection => GameSubsector.all(:order => :name)
f.actions
end
I feel the javascript is even maybe not fired.
The jquery I use is located on app/assets/javascript/admin/active_admin.js (I changed config so it loads this javascript when loading active admin pages)
jQuery.ajaxSetup({
'beforeSend': function(xhr) { xhr.setRequestHeader("Accept", "text/javascript"); }
});
$.fn.subSelectWithAjax = function() {
var that = this;
this.change(function() {
$.post(that.attr('rel'), {id: that.val()}, null, "script");
});
};
$("#game_game_sector_id").subSelectWithAjax(); //it it found in my view???
Finally I created a view as this expert adviced: in app/views/layout/ game_subsectors_by_game_sector.js.erb
$("#game_game_subsector_id").html('<%= options_for_select(#game_subsectors.map {|sc| [sc.name, sc.id]}).gsub(/n/, '') %>');
I'm not sure I have out it in the right place though...
What you need is:
Inspect with your web browser console your selects, and use a CSS selector to create a jQuery object for the sector select, something like:
$('#sector_select')
Append to this object a handler, so when it changes AJAX request is fired:
$('#sector_select').change(function(){
$.ajax('/subsectors/for_select', {sector_id: $(this).val()})
.done(function(response){ // 3. populate subsector select
$('#subsector_select').html(response);
});
});
See 3 in code, you need to inspect to get the right CSS selector. Be sure you are getting the expected response in the Network tab of your web browser inspector(if using Chrome).
You need a controller that answers in /subsectors/for_select, in the file app/controllers/subsectors_controller.rb:
class SubsectorsController < ApplicationController
def for_select
#subsectors = Subsector.where sector_id: params[:sector_id]
end
end
You need a view that returns the options to be populated app/views/subsectors/for_select.html.erb:
<% #subsectors.each do |ss| %>
<option value="<%= ss.id %>"><%= ss.name %></option>
<% end %>
You need a route:
get '/subsectors/for_select', to: 'subsectors#for_select'

clear input after search

I have a search box on my site. The search works well. I'd like the search field to clear after you submit a search. I have it working to clear onclick but the onsubmit doesn't work. It is definitely submitting a search because I can see the results.
js
<script type="text/javascript">
function clearDefault(el) {
if (el.defaultValue==el.value) el.value = ""
}
function clearText(thefield){
if (thefield.defaultValue==thefield.value)
thefield.value = ""
}
</script>
view
<%= form_tag guidelines_path, :class => 'navbar-search pull-right', :onSubmit=>"clearText(this)",:method => :get do %>
<%= text_field_tag :search, params[:search], :class => 'search-query', :placeholder=>"Search", :ONFOCUS=>"clearDefault(this)" %> <% end %
>
Th onsubmit isn't an event of a text field but rather the form it belongs to. If you move your onsubmit attribute to the form, it should clear it.
Rather than pass the field as a parameter, why not just fetch the field by it's class? So using jquery:
function clearText(){
search = $('.search-query');
if (search.defaultValue==search.value)
search.value = ""
}
If you can't use jQuery for some reason you could try and assign the form field an ID and use document.getElementById() instead?

Select Box onClick - Rails

I have a Rails application that in the erb code, I use a select box. What I would like to do is reload the page passing the sort parameter. My controller already handles it, but I don't know how to reload the page with the selected value from my select box. Here is my code:
<% #options = {:latest => 'lastest' , :alphabetical => 'alphabetical', :pricelow => 'price-low', :pricehigh =>'pricehigh'} %>
<%= select_tag 'sort[]', options_for_select(#options), :include_blank => true,:onchange => "location.reload('location?sort='+this.value)"%>
Have you considered using an ajax call on your list box? If you have a method on your controller that returns just the sorted list, based on sort parameter, then you could do:
<% #options = {:latest => 'lastest' , :alphabetical => 'alphabetical', :pricelow => 'price-low', :pricehigh =>'pricehigh'} %>
<%= select_tag 'sort[]', options_for_select(#options), :include_blank => true,:onchange => remote_function(:url => {:controller => 'your_controller', :action => 'list_sort_method'}, :with => "'sort='+this.value", :update => "div_containing_list") %>
If you don't want to use AJAX, then put a form_tag around your code.
Take a look at the Redmine source code on http://redmine.rubyforge.org/svn/trunk. The UsersController does something similar - there's a combo box that allows a filter. Selecting the combo reloads the page.

Categories

Resources