I am looking to update a url when a selection is made from a dropdown. I would like to have the query to be dynamic, here is the following code:
<select id="mySchool" onchange="this.form.submit()">
<% #schools.each do |school| %>
<option value="<%= school.id %>"><%= school.name %></option>
<% end %>
</select>
<%= link_to "Apply School", "schools/assign_users?user_id=#{#user.id}&school_id=", :class => "btn btn-primary", :type => "button" %>
Can anyone point me in the right direction?
This is not the best way to create select in rails. You should rather use rails select_tag helper like this:
<%= select_tag 'school_id', options_for_select(#schools.collect{ |s| [u.name, u.id] }), id: "mySchool" %>
I am looking to update a url when a selection is made from a dropdown.
I think instead of showing the link upfront you should show the link only when a user select a value from dropdown so your code should be something like this:
<%= select_tag 'school_id', options_for_select(#schools.collect{ |s| [u.name, u.id] }), id: "mySchool" %>
<div id="schoolLink"></div>
#_link.html.erb
<%= link_to "Apply School", "schools/assign_users?user_id=#{user.id}&school_id=#{school.id}", :class => "btn btn-primary", :type => "button" %>
Now make a route to which you want to send the ajax request to:
post 'selected_school/:id' => 'school#selected', as: "select_school"
write a js function which will send ajax request on changing values in dropdown
$(document).on("change","#mySchool",function(e){
var school_id = $(this).val();
$.ajax({
type: "POST",
url: "/selected_school",
data: {id : school_id }
});
});
Find school and user inside controller and then finally render link by js
#school_controller.rb
def selected
#school = School.find(params[:id]) # find school by the passed id
#user = current_user # your logic to find user
end
#app/views/school/selected.js
$("#schoolLink").html("<%=j render partial: 'link', locals: {user: #user, school: #school} %>");
For details checkout Working with Javascript in Rails
Related
Hello all !
Im using rails and in the steps I would like the user to (on the same page) :
Enter his address
Filling the form
Submit the form
Click to submit
Update the view to show the address
The view updated
Should I use Stimulis or Ajax? I don’t quite understand which would be more useful!
Because i try to use simply JS but it’s was not DRY and not really simple:
// file.js
document.querySelector(".form").addEventListener('submit', function () {
adress_form = document.querySelector(".adress_form");
adress_form.style.display="none";
document.location.reload();
display_adress = document.querySelector(".display_adress");
display_adress.style.display = "block";
});
#file.html.erb
<div class="display_adress">
<% if current_user.line1? && current_user.postal_code? && current_user.city? %>
<p>Mon adresse actuel : <%= current_user.line1 %>, <%= current_user.city %> <%= current_user.postal_code %></p>
<% end %>
</div>
<div class="address_form">
<%= simple_form_for(current_user, remote: true, html: { id: "addddd"}) do |f| %>
<%= f.input :line1, label: 'Mon adresse' %>
<%= f.input :city, label: 'Ville' %>
<%= f.input :postal_code, label: 'Code Postal' %>
<%= f.submit %>
<% end %>
</div>
To resume, i want the user to enter his address on the form, to submit, to update my database and to update the view with the new address the user submitted
Thanks for helping!
You can respond in the controller javascript. For example:
file.html.erb
<%= simple_form_for(current_user, remote: true, format: :js, html: { id: "addddd"}) do |f| %>
users_controller.rb
def create
# do your business logic
render 'create
end
users/create.js.erb
document.getElementById("formId").innerText = "Othe html text or you can call render(*)"
I have a form and I need to have 2 submit buttons. This seems like the only way I can think to do to accomplish what I want.
The goal is to use one form to send to one method and then possibly redirect to another method depending on the params passed because the functions will be different.
Form:
<%= form_for(:mass, url: mass_product_variant_category_path, method: :get, remote: true) do |mass| %>
<%= mass.submit "Update All", name: "All", class: "btn btn-light" %>
<%= mass.submit "Update Files", name: "Files", class: "btn btn-light" %>
<% #Stuff.each do |variant| %>
<%= check_box_tag 'store_variant_ids[]', variant.id %>
<% end %>
...
<% end %>
I tried: <%= submit_tag "Submit", name: "All" %>, also not working.
The html:
<input type="submit" name="File" value="Update Files" class="btn btn-light" data-disable-with="Update Files">
Controller:
def mass_product_variant_category
#stuff = Stuff.where(store_variant_id: params[:store_variant_ids])
if params[:commit] == "File"
redirect_to edit_multiple_stuffs_path(stuffs: #stuffs)
else
respond_to do |format|
format.js
end
end
end
The params that get passed are:
{..."mass" => {hidden_field: "int"}, "other_attributes" => ["int"]...}
This is due to using remote: true, but not sure why or how.
How can I pass through a param based on the submit form?
I've read other SO posts on this, but there are very few and none seem to have a good or any accepted answers. I also cannot use hidden_fields due to needing a redirect based on submit button used.
Is there a "Rails" way to do this without needing to add javascript or is that my only option?
I solved this by using a hidden_field_tag within the form that gets filled in based on the submit button used through an onclick. I can then check the hidden_fields param in the controller.
The "name" attribute maps to the name in the params hash. For this case you should do something like:
if params["File"]
# Something
elsif params["All"]
# Other thing
else
# Default
end
I am using a sidebar that searches and generates a list (within the sidebar) I want the main page to remain unchanged when searching with the sidebar. I believe this requires some JS, but I know nothing about JS.
my navbar is in a div _navbar.html.erb
main page is basically any other page being generated
here is my code: https://github.com/nrkfeller/ratingapplication
You need to use AJAX with rails. Here is how it may work for you:
Add a :remote => true to your form and :'data-update-target' => 'update-container' to specify where you want the search results to go. You might want to avoid using the courses_path, but use form_tag({:controller => courses, :action => 'search'} to directly state where you want the form to be submitted.
<%= form_tag courses_path, method: :get, :remote => true ,class: "navbar- form navbar-right", :'data-update-target' => 'update-container' , role: "search" do %>
<p>
<%= text_field_tag :search, params[:search], class: "form-control" %>
<%= submit_tag "Search",:disable_with => 'Please wait...', name: nil, class: "btn btn-default" %>
</p>
<% end %>
Add this to your sidebar. This is where the partial with the results will come:
<div id="update-container"></div>
Add the javascript`` to put it where it is supposed to be when the request finishes:
<script>
$(function() {
$('form[data-update-target]').on('ajax:success', function(evt, data) {
var target = $(this).data('update-target');
$('#' + target).html(data);
});
});
Add a partial named _search_results.html.erb <- this is where your results go.
<!-- arbitrary code -->
<%= #results.each do |result| %>
<%= result %>
In your controller:
def search
#results= #your search code
render :partial => 'search_results', :content_type => 'text/html'
end
This is will get the functionality you wanted. Beware, this is more of a pesudocode than an exact implementation of what you want to do. You have to fill in the gaps.
I hope I was helpful!
So I have a form that adds codes to an appointment in rails. There are 2 types of codes, regular codes that get added straight to the apt and wildcard codes that return a list of codes that contain the query (ex. 800* returns anything with 800 in it).
What I need to do is have any regular codes get added to the appointment and return the appointment page if no wildcard codes are selected. If wildcard codes are selected, I need to render a partial that toggleslides out with the search results. If both wildcard and regular codes are selected I need the toggleslide but also have the regular codes updated on the codes table on the page.
The problem I'm having is when just regular codes are selected, the toggleslide is still being called and populated with the appointment page in it.
I have the form that does this set to remote and in a js file I have the ajax response do the toggleslide and populate it with the response. Is there a way to override the ajax response in the controller and just redirect to the appointment page if no wildcard codes are selected?
Or is there a better way to do all this? I tried using a js template but keep getting a 406 error. Or I fix the 406 error by removing any respond_to calls but the toggleslide doesn't get called.
In my js file in my assets.
$(document).ready(function() {
$("#custom_codes_form_1").on("ajax:success", function(e, data, status, xhr) {
$('#my_lists_modal_1').hide();
$('#search_code_results').html(data);
$('html, body').animate({ scrollTop: 0 }, 'slow');
$('#search_code_results').show('blind', {direction: "left"});
});
return false;
});
In my controller. #all_codes is the list of codes returned on a search query.
This is in the add_code_list_codes method:
if !#all_codes.nil?
render :partial => "/encounter/code_search_results", :content_type => 'text/html', :locals => {:codes => #codes, :apt => #apt, :all_codes => #all_codes, :diagnoses_search => true, :type => #type}
else
respond_to do |format|
format.html {redirect_to encounter_show_path(:id => #apt.id)}
end
end
Here's the form.
<%= form_tag({:controller => :encounter, :action => :add_code_list_codes, :id => #apt.id}, :class => 'form-horizontal', :id => "custom_codes_form_#{cl.id}", :remote => true ) do %>
<% CodeType.by_name.all.each do |ct| %>
<h4 class="small_bottom_margin"><%= ct.display_name %></h4>
<div class="control-group">
<% cl.code_list_items.all_by_code_type(ct.id).each do |cc| %>
<%= label_tag :codes, :class => 'checkbox' do %>
<% if cc.code %>
<%= check_box_tag 'codes[]', cc.id %> <strong><%= cc.code.code %></strong> - <%= cc.name_override ? cc.name_override : cc.code.name %>
<% else %>
<%= check_box_tag 'codes[]', cc.id %> <strong><%= cc.search_criteria %></strong> - Wildcard
<% end %>
<% end %>
<% end %>
</div>
<% end %>
<%= submit_tag("Add Selected Charges", :class => 'btn', 'data-disable-with' => "Adding Charges") %>
<% end %>
using this example on dynamic list https://github.com/sandeepleo11/Dynamic-Select-Menus-in-Rails-3 I managed to get dynamic select in my form where I add a car, so when I select a carname in the next select field I get only car models that belongs to car I selected, Workin fine in this form.
So I decided to get this thing also in my search form, you select a car and based on that you select a car model and get the results. here is the website with search form http://ec2-107-22-183-238.compute-1.amazonaws.com/cars.
the problem here is that when I select a car I get ActionController::RoutingError (No route matches "/dynamic_search/6"): in console, 6 means I picked a car name who's id is 6 and the select field for carmodels displays all models available.
here is some code I have for the search form and dynamic search:
_search.html.erb
<%= form_for #search do |f| %>
<%= f.label :carname_id_equals, "Select Car Make" %>
<%= f.collection_select :carname_id_equals, Carname.order('name ASC').all, :id, :name, :include_blank => 'All' %>
<%= f.label :carmodel_id_equals, "Select Model" %>
<%= f.collection_select :carmodel_id_equals, Carmodel.order('name ASC').all, :id, :name, :include_blank => 'All' %>
<% end %>
dynamic_search.js.erb
$('#search_carmodel_id').empty();
<% for carmodel in #carmodels %>
// alert(<%= carmodel.id %>);
$('#search_carmodel_id').append($("<option></option>").attr("value",<%= carmodel.id %>).text('<%= carmodel.name %>'));
<% end %>
routes.rb
post "dynamic_carmodels/:id" => "cars#dynamic_search"
controller
def dynamic_search
#carmodels = Carmodel.find_all_by_carname_id(params[:id])
respond_to do |format|
format.js
end
end
application.js
jQuery(document).ready(function() {
// jQuery('#search_carmodel_id_equals').html("<option value=''>Select Carmodel</option>");
jQuery('#search_carname_id_equals').change(function() {
var data=$('#search_carname_id_equals').val();
$.ajax({
type: "POST",
url: "http://"+location.host+"/dynamic_search/"+data,
data: data,
beforeSend: function()
{
// alert('hi');
//$('#status').html('<img src="loading.gif">');
},
success: function(response)
{
// alert(response);
// $('#search_carmodel_id_equals').html(html); //dynamic_search.js.erb
// $('#status').html(html);
}
});
});
});
Solved:
routes is the problem:
post "dynamic_carmodels/:id" => "cars#dynamic_search"
should be
post "dynamic_search/:id" => "cars#dynamic_search"
and dynamic_search.js.erb
$('#search_carmodel_id_equals').empty();
<% for carmodel in #carmodels %>
// alert(<%= carmodel.id %>);
$('#search_carmodel_id_equals').append($("<option></option>").attr("value",<%= carmodel.id %>).text('<%= carmodel.name %>'));
<% end %>strong text