rails 3 dynamic select field with jQuery - javascript

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

Related

How to avoid sending params of fields deleted using JQuery remove()

In this code I was trying to remove fileds for nested_attributes using ajax :remote => ture to avoid reloading
the whole page in browser. Although fileds in fields_for was removed from DOM and association was removed from database, the fields of the nested attributes
still exist in page source and raise ActiveRecord::RecordNotFound error when trying to send params to update action of parent model
consider the following code:
_artist_form.html.erb
<%= form_for #artist do |f| %>
<%= f.label :name %>
<%= f.text_field :name %><br/>
<%= f.label :style %>
<%= f.text_field :style %><br/>
<%= f.fields_for :songs do |song_builder|%>
<div id = 'song_<%= song_builder.object.id %>_div'>
<%= song_builder.label :title %>
<%= song_builder.text_field :title %><br/>
<%= song_builder.label :lyrics %>
<%= song_builder.text_area :lyrics %><br/>
<%= link_to 'Remove song', delete_song_path(:a_id => #artist.id, :s_id => song_builder.object.id),
:method => :delete , :remote => true %>
</div>
<% end %>
<%= f.submit 'Save' %>
<% end %>
routes.rb
Rails.application.routes.draw do
...
delete '/artists/remove_song', :to => 'artists#delete_song', :as => :delete_song
end
application_controller.rb
class ArtistsController < ApplicationController
def edit
...
end
def update
#artist = Artist.find(params[:id])
if #artist.update(artist_params) #=> error Couldn't find Song with ID=2 for Artist with ID=2
redirect_to artist_path(#artist)
else
flash[:errors] = #artist.errors.full_messages
render :edit
end
end
...
def delete_song
#song_id = params[s_id]
aritst = Artist.find(:params[a_id])
song = artist.songs.find(#song_id)
song.delete
respond_to do |format|
format.js {render 'delete_song.js.erb'}
end
end
end
delete_song.js.erb
$('#song_<%= #song_id %>_div').remove() ;
Error
Couldn't find Song with ID=2 for Artist with ID=2
how to prevent sending params of removed fields by $(...).remove() to update action?
I tried to find a solution for this error. So according to charlietfl comment, I tried to store delete status somewhere locally, then rails can delete association later. So I modified the code as following:
deleting all remote script code including delete_song.js.erb file and delete_song action and delete route. then I allowed marking nested attribute for delete in Artist model file:
accepts_nested_attributes_for :songs, :allow_destroy => true
then adding delete button in _artist_form.html.erb file as following:
<%= button_tag 'x' , :class => 'close_sign', :type => 'button', :onclick => "$('#song_#{song_builder.object.id}_destroy').val('true'); $('#song_#{song_builder.object.id}_div').hide()" %><br/>
and a hidden flied to fields_for as below:
<%= song_builder.hidden_field :_destroy, :id => "song_#{song_builder.object.id}_destroy" %>
and allowing :songs_nested_attributes => [:title, :lyrics, :_destroy] in song_params
once user remove the song field, it will be hidden and marked for destroy later

Updating URL query string with JS / Rails and a dropdown form

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

How to make a input field visible when a button is clicked or create the same field when a button is clicked for ruby on rails

rails newbie here.
this is my current form
<%= f.input :campaign_name , :input_html => {:style=> 'width: 300px'} %>
<%= f.input :date_range, :input_html => {:style=> 'width: 300px'}%>
<%= f.label :first_event %>
<%= f.collection_select :first_event, eventNames, :to_s, :to_s, include_blank: true %>
<br><br><br>
<%= f.label :second_event %>
<%= f.collection_select :second_event, eventNames, :to_s, :to_s, include_blank: true%>
what i want is this, when user clicks "add filter" i want another field to pop up with the same eventNames array as a collection select.I tried to create another button and get it's tag and if its not the submit button and its add filter button render another form.
but this is terribly bad as a interface and as a user experience.
i want my user to be able to remove the second event field at anytime, without having to submit the form.
So i need to add another button in it to remove the newly made visible form.
How can i achieve this
As i said in my comment if you have a restriction that a user could add only a single or lets say a fixed number of filters then you can simply show and hide your collection by js. Your form would have a hidden collection list
<%= f.input :campaign_name , :input_html => {:style=> 'width: 300px'} %>
<%= f.input :date_range, :input_html => {:style=> 'width: 300px'}%>
<%= f.label :first_event %>
<%= f.collection_select :first_event, eventNames, :to_s, :to_s, include_blank: true %>
<br><br><br>
<%= f.label :second_event %>
<%= f.collection_select :second_event, eventNames, :to_s, :to_s, include_blank: true%>
<%= f.label :third_event, class: "hidden" %>
<%= f.collection_select :third_event, eventNames, :to_s, :to_s, include_blank: true, class: "hidden"%>
hide your collection by css
.hidden{display: none;}
and show it by js when a user click on add filter, assuming it's a link you could do:
= link_to "Add Filter", "#", id: "add-filter"
$(document).on("click","#add-filter", function(e){
$(".hidden").show();
e.preventDefault();
});
If user can add multiple filters then you'll need to add them by ajax. For ajax follow these steps:
a. Create a custom route for your action:
post "/filter" => "your_controller#add_filter", as: "filter"
b. create your link for adding filter:
<%= link_to "Add Filter", filter_path, id: "add-filter", data: {event_id: "2", url: filter_path}%>
c. Get event_id by js and send a ajax request:
$(document).on("click","#add-filter".function(e){
var eventId = $(this).data("eventId");
var url = $(this).data("url");
$.ajax({
type: "POST",
url: url,
data: {id: eventId}
});
})
d. Create add_filter action in your controller:
def add_filter
#event_id = params[:id]
respond_to do |format|
format.js
end
end
e. Create your new collection and append it by js in app/views/your_controller/add_filter.js.erb file
var label = "<%=j label_tag "#{#event_id.humanize}_event" %>"
var collection = "<%=j collection_select(:resource, "#{#event_id.humanize}_event".to_sym , eventNames, :to_s, :to_s, include_blank: true) %>"
$("#form_id").find("select").last().after(label).after(collection);
$("#add-filter").data("eventId","<%=j #event_id + 1 %>");
You'll have to use humanize or number_and_words to convert your #event_id to words format and also you'll have to change :resource accordingly

dynamically displaying data in text field ruby on rails

Hello guys i am trying attempt a dynamic select here. as soon as i select the customer his total value in the bill should come and get displayed in the text field tag.
the view
jQuery(document).ready(function(){
jQuery(".customerid").bind("change", function() {
var data = {
customer_id: jQuery(".customerid :selected").val()
}
jQuery.ajax({
url: "get_cust_bill",
type: 'GET',
dataType: 'script',
data: data
});
});
});
</script>
<div class ="customerid"><%= f.label :customer_id %>
<%= f.collection_select :customer_id, Customer.all, :id, :name, options ={:prompt => "-Select a Customer"}, :class => "state", :style=>'width:210px;'%></div><br />
<div class ="customerbill">
<%= f.label :total_value, "Total Value" %>
<%= render :partial => "customerbill" %>
js.erb file
jQuery('.customerbill').html("<%= escape_javascript(render :partial => 'customerbill') %>");
the customerbill partial
<% options = []
options = #cust_bill.total_value if #cust_bill.present? %>
<%= text_field_tag "total_value", options %>
in contoller
def get_cust_bill
#cust_bill = CustomerBill.find_all_by_customer_id(params[:customer_id]) if params[:customer_id]
end
I feel the problem lies in the partial, the way i am calling the options so can anyone guide me how to get the value in text field??? thank in advance.
From what I understand, total_value text field does not show anything. Could you try to output the value of options and check if it always has a value? I suggest you check out the documentation for the text_field_tag. Basically, it accepts three variables like this:
text_field_tag(name, value = nil, options = {})
i was using getJSON method....and i feel that can be used here. hope the followng works.
jQuery(document).ready(function()
{
jQuery(".customerid select").bind("change", function() {
var data = {
product_id: jQuery(this).val()
}
jQuery.getJSON(
"/controller_name/get_cust_bill",
data,
function(data){
var result = "";
res = parseFloat(a[1]);
jQuery('.price input').val(res);
});
});
});
controller
def get_cust_bill
#cust_bill = CustomerBill.find_all_by_customer_id(params[:customer_id]).map{|p| [p.price]} if params[:customer_id]
respond_to do |format|
format.json { render json: #cust_bill }
end
end
so no need of calling js. erb partial you can simply have
<div class = "price"><%= f.input :price, :label => 'Price', :input_html => { :size => 20} %></div><br/>
all the best :)

jQuery Tokeninput Error in Rails

I'm trying to use jQuery Tokeninput as shown in Railscast #258 (revised). When I enter something in the tokeninput field, the field does not dropdown with results and I get the following javascript error: Uncaught TypeError: Cannot call method 'replace' of undefined.
My json data works fine when I do a manual query on it, and the server request looks fine. I am trying to search the content column in my issues table, so I set propertyToSearch to "content".
Here is my code:
coffeescript:
jQuery ->
$('#fact_issue_tokens').tokenInput "/issues.json"
theme: 'facebook'
zindex: 11001
propertyToSearch: 'content'
tokenValue: 'content'
hintText: 'Enter an issue'
preventDuplicates: true
Issue Model:
def self.tokens(query)
issues = where("content like ?", "%#{query}%")
if issues.empty?
[{id: "<<<#{query}>>>", content: "New: \"#{query}\""}]
else
issues
end
end
def self.ids_from_tokens(tokens)
tokens.gsub!(/<<<(.+?)>>>/) { create!(content: $1).id }
tokens.split(',')
end
Issues Controller:
def index
#issues = Issue.order(:content)
respond_to do |format|
format.html
format.json { render json: #issues.tokens(params[:q]) }
end
end
Form:
<%= form_for(Fact.new, :url => kase_facts_path(current_kase), :html => {:class => "form-
inline"}) do |f| %>
<%= f.text_field :page, placeholder: 'Page' %>
<%= f.text_field :description, placeholder: 'Description' %>
<%= f.label :issue_tokens, 'Issue tags' %>
<%= f.text_field :issue_tokens %>
<%= f.hidden_field :source_id, :value => #source.id %>
<%= f.submit 'Add Fact' %>
<% end %>
#Scott you try this
jQuery ->
$('#fact_issue_tokens').tokenInput '/issues.json'
theme: 'facebook'
tokenLimit: 5
minChars: 4
preventDuplicates: true
searchingText: "Enter an issue..."
prePopulate: $('#fact_issue_tokens').data('load')
and think on your index because you are using (:content) not name might be your problem. I am bot sure why but i used title and i had a problem, i thought it was mysql or something.
When you visit
http://localhost:3000/issues.json
Do you get the JSON data?
Edit.
Can you please try this for your form?
<div class="field">
<%= f.label :issue_tokens, "Issues" %><br />
<%= f.text_field :issue_tokens, data: {load: #fact.issues} %>
</div>

Categories

Resources