Custom country/state dropdowns with rails - javascript

I been diggins some days on gems for country and state/province selection. Some are great (like country-state-select) but not for my needs.
The almost mandatory country_select gem is good but lacks states. Nevertheless is based on this very cool gem called countries. Gem countries really puts together a lot of good info, lets say Mozambique and its subdivisions, and so on, for over 300 countries, and includes i18n.
Having countries gem in the app, all is needed is some javascript to interact with it. Calls are made with this:
country = ISO3166::Country.new('US')
Here is the form:
<%= simple_form_for(#order) do |f| %>
<div><%= f.input :country %></div>
<div><%= f.input :state %></div>
<%= f.button :submit, t('.submit') %>
<% end %>
<script type="text/javascript">
states_drop_down = $("#order_state");
$("#order_country").change(function() {
// How to make this work?
<% unless params[:country].nil? %>
states_drop_down.clearAttributes();
<% ISO3166::Country.new(params[:country]).states.each do |state| %>
states_drop_down.setAttribute(<%= state[:name] %>, <%= state[:alpha2] %>); // How to log to check if new attributes are present?
<% end %>
states_drop_down.reload(); // How to reload the state simple_form input?
<% end %>
});
The goal is the known one, to populate state selector with correct country every time the country dropdown changes. Any help? Thanks.

I found a solution, even though is not using gem countries anymore. Data is seeded to database and pulled from there. Found the data here.
Then all is needed is few steps:
// 1. new action at controller, in my case was orders. This receives the calls and renders the views.
def update_states
country = Country.find(params[:nation_id])
#states = country.states
respond_to do |format|
format.js
end
end
// 2. new get at routes to find the new action
get "orders/update_states", as: "update_states"
// 3. simple_form with collections. Note uses nation to avoid the simple_form country selector error.
<%= simple_form_for(#order) do |f| %>
<div><%= f.input :nation, collection: #countries %></div>
<div><%= f.input :state, collection: #states %></div>
<%= f.button :submit, t('.submit') %>
<% end %>
// 4. new doc at app/views/states/_state.html.erb to render inside the dropdown selector.
<option value="<%= state.id %>"><%= state.name %></option>
// 5. new lines at app/assets/javascripts/orders.js.coffee to listen to nation or country selector.
$ ->
$(document).on 'change', '#order_nation', (evt) ->
$.ajax 'update_states',
type: 'GET'
dataType: 'script'
data: {
nation_id: $("#order_nation option:selected").val()
}
error: (jqXHR, textStatus, errorThrown) ->
console.log("AJAX Error: #{textStatus}")
success: (data, textStatus, jqXHR) ->
console.log("State selection is working!")
// 6. and app/views/orders/update_cities.js.cofee, the piece that close the circle. This actually renders the info and views.
$("#order_state").empty()
.append("<%= escape_javascript(render(:partial => #states)) %>")
Must thanks Kernel Garden, I found the javascript I was looking here.

Related

Rails - pass a parameter to controller from form select dropdown

I have 2 models: Team and Quest. When creating a new team, I have a drop-down of all the quests. When a quest is selected, I want to display information about the quest.
My understanding is that everything in the form is on the client side and AJAX is required to pass the selected quest to the server side. My code is based on this Stack Overflow answer.
Here is how I constructed my form:
app/views/teams_form.html.erb
<%= form_for(#team) do |f| %>
<fieldset>
<ol>
<li>
<%= f.label :name %>
<%= f.text_field :name %>
</li>
<li>
<%= f.label :quest_id %>
<%= f.select :quest_id,
options_from_collection_for_select(#quests, :id, :name),
{}, {remote: true, url: '/teams/new', method: 'get'} %>
</li>
<% if #x != nil && #x.id != nil %>
<li><%= #x.id %></li>
<% end %>
</ol>
<p>
<%= f.submit %>
</p>
</fieldset>
<% end %>
app/controllers/team_controller.rb
def new
#team = Team.new
#quests = Quest.all
respond_to do |format|
if params[:quest_id] != nil
#x = Quest.find(params[:quest_id])
end
format.html #new.html.erb
format.json
format.js
end
end
My goal was to pass the :quest_id parameter from the form to the #x variable and use that in the form.
This has produced nothing. I'm not getting the parameter in the controller and I'm not sure what I'm missing.
As per the description shared it seems like the you are unable to get the value of the selected item from the dropdown.
Below mentioned code is used for selecting value from dropdown also you can inspect the same using developer tools of the browser.
quest = $("#quest_id").val();
Note: Assuming the selector id is quest_id, change it according to your form.
Now, you can call the ajax using the below mentioned code.
$.ajax({
type: "GET",
url: "/teams/new",
data:{ quest_id: quest },
dataType: "json",
success:function(data){
# logic for using ajax result
}
Hope it helps!!
Finally got this working, wanted to post if anyone sees this and is having the same problem:
I went with a separate AJAX request since that was being suggested
app/views/teams_form.html.erb
<script>
$(document).ready(function() {
$('#team_quest_id').change(function() {
$.ajax({
url: "/teams/new",
data: {quest_id: $("#team_quest_id option:selected").val()},
dataType: "script",
method: "get",
success: function(r){}
});
});
});
</script>
I moved the location of the parameter assignment
app/controllers/team_controller.rb
def new
#team = Team.new
#quests = Quest.all
if params[:quest_id] != nil
#x = Quest.find(params[:quest_id])
end
respond_to do |format|
format.html #new.html.erb
format.json
format.js
end
end
And most importantly - I created a js file to render my form
app/views/new.js.erb
$('#new_team').html("<%= j (render 'form') %>");
This video was extremely helpful
The code in your question is almost correct, you forgot to nest the attributes in data.
<% # app/views/teams_form.html.erb %>
<%= f.select :quest_id,
options_from_collection_for_select(#quests, :id, :name),
{}, {remote: true, url: '/teams/new', method: 'get'} %>
<% # should be: %>
<%= f.select :quest_id,
options_from_collection_for_select(#quests, :id, :name),
{}, {data: {remote: true, url: '/teams/new', method: 'get'}} %>
<% # or even better, use the path helper instead of the hard coded path %>
<%= f.select :quest_id,
options_from_collection_for_select(#quests, :id, :name),
{}, {data: {remote: true, url: new_team_path, method: :get}} %>
Having set the attributes correctly, we still need to fix the form further. On page request the browser will request the form, but #x will never be set. Since ERB will not be send to the client we'll need to add a handle to find our quest container element back.
<% # app/views/teams_form.html.erb %>
<% if #x != nil && #x.id != nil %>
<li><%= #x.id %></li>
<% end %>
<% # should be something like %>
<li id="quest-info-container"></li>
Now in the controller split of the HTML request from the JS request.
# app/controllers/teams_controller.rb
def new
respond_to do |format|
format.html do
#team = Team.new
#quests = Quest.all
end
format.js do
#quest = Quest.find(params.dig(:team, :quest_id))
end
end
end
You could simplify the above by sending the select data-path to another url that handles the quest preview.
Now we need to render the preview in our container we need 2 files for this, first of how the resulting structure should look. Keep in mind that this will be rendered inside the container.
<% # app/views/teams/_quest_preview.html.erb %>
<% # Here comes what you want to display about the quest. You can give this %>
<% # file another name if you like. You have #quest to your disposal here. %>
<%= #quest.id %> <strong><%= #quest.name %></strong>
Now we only need a JavaScript file that loads the above structure into our created handle.
<% # app/views/teams/new.js.erb %>
handle = document.getElementById('quest-info-container');
handle.innerHTML = '<%= j render('quest_preview') %>';
The j is an alias for escape_javascript. If the partial is not in the same directory use <%= j render('other_dir/some_partial') %> instead.

select user and then dropdown of his challenges

A user has_many challenges.
When a user is selected...
<%= f.select :user_id, options_for_select(#challengers.collect { |challenger| [challenger.full_name] }) %>
... how can we show another dropdown with a list of his challenges?
<%= f.select :challenge_id, options_for_select(#challenger_challenges.collect { |challenged| [challenged.full_challenge]}) %>
In other words, how can we make "#challenger_challenges = the selected user's challenges"?
As it stand I get an error undefined method 'collect' for nil:NilClass since #challenger_challenges is nil.
OPTION 1
In challenges_controller I could do this:
#challengers = User.all
#challenger = User.find(params[:challenger_selected]) if (params[:challenger_selected]).present?
#challenger_challenges = #challenger.challenges
And then I would just need a way to refresh the page once a user is selected so that the user ID is passed in the params as :challenger_selected
OPTION 2
Achieve the aim of this question without the need of a page refresh. *Preferable
UPDATE
Based upon the comments below I realize I need to elaborate.
A user has_many challenges.
A user can create a duel.
In a duel there are two duelers.
The creator of the duel selects his own :challenge_id and then he selects the other dueler as well as one of his :challenge_id and then sets the #duel.consequence the dueler will have to do if he fails his challenge. The other dueler will get a duel request notification and then has the choice to accept or decline the conditions of the duel.
challenges.show.html.erb
<%= render 'duels/form' %>
duels/_form.html.erb
<%= simple_form_for(#duel) do |f| %>
<%= f.fields_for :duelers do |dueler| %>
<%= f.hidden_field :challenge_id, :value => #challenge.id %>
<%= #challenge.full_challenge %>
<% end %>
<%= f.fields_for :duelers do |dueler| %>
<%= render 'duels/dueler_fields', :f => dueler %>
<% end %>
<%= button_tag(type: 'submit', class: "btn", id: "challenge-create-save") do %>
Request Duel
<% end %>
<% end %>
duels/_dueler_fields.html.erb
<%= f.select :user_id, options_for_select(#challengers.collect { |challenger| [challenger.id] }) %>
# Trying to make this responsive to the user that is selected above
<%= render 'challenges/select', :f => f %>
<script>
$('#duel_duelers_attributes_1_user_id').change(function () {
var challenger_id = $(this).find(":selected").val();
var address = "<%= select_path %>".concat(challenger_id);
$.get(address, function(data) {
$("#duel_duelers_attributes_1_challenge_id").html(data);
});
});
</script>
routes
get 'challenges/select/:id' => 'challenges#select', as: 'select'
challenges/_select.html.erb
<%= f.select :challenge_id, options_for_select(#challenger_challenges.collect { |challenged| [challenged.full_challenge]}) %>
challenges_controller
def select
if (params[:challenger_id]).present?
#challenger = User.find(params[:challenger_id])
else
#challenger = User.find(1)
end
#challenger_challenges = #challenger.challenges
end
Credit for this should go to #Fallenhero - I am just explaining it in more detail.
You need to be able to identify the select tag.
<%= f.select ..., :html => {:id => :first} %>
You also need somewhere to put the second one.
<div id="second"></div>
Using jQuery:
$('#first').change(function () {
var challenger_id = $(this).find(":selected").val();
var address = "<%= [prints address to new select tag] %>".concat(challenger_id);
$.get(address, function(data) {
$("#second").html(data);
});
});
The address Ruby prints out should look something like challenges/select/ depending on how you want to design it. The / at the end is important.

Live Search with AJAX Ruby on Rails

I'm following the railscasts rails ajax tutorial and geting into some trouble. Everything went well, except the live keyup. The live search does not work, I have to click the search button to get the result.
Here is my application.js
$("#emos_search input").keyup(function() {
$.get($("#emos_search").attr("action"), $("#emos_search").serialize(), null, "script");
return false;
});
index.html.erb
<%= form_tag emoticons_path, :method => 'get', :id => "emos_search" do %>
<p>
<%= text_field_tag :search, params[:search] %>
<%= submit_tag "Search", :name => nil %>
</p>
<div id="emos"><%= render 'emos' %></div>
<% end %>
emoticons_controller.rb
def index
#emoticons = Emoticon.search params[:search]
end
emoticon.rb
def self.search(search)
if search
where('name LIKE ? or emo LIKE ?', "%#{search}%", "%#{search}%")
else
scoped
end
end
I don't know what is the problem. I think I already followed the steps in tutorial. And there is nothing showed in js console.

Escape_javascript problem

I have a set of dependent dropdown menus on my user/edit page. The user selects the parent dropdown, which then limits the selections available in the child dropdown. The user can add multiple additional sets of parent/child dropdowns. Product is the parent. Variety is the child.
This all works great unless a variety is entered into the database that includes double quotes. When that happens, it breaks the javascript and the trigger to render the partial doesn't work at all.
Single quotes do not cause this problem, nor do any other characters that I've tried. So this problem is specific to double quotes. I thought that escape_javascript was the answer here, but I've tried placing it in many different places in the code and nothing has worked. It's very possible that I just don't know exactly where the helper and it's parenthesis are supposed to go.
The api documentation is terrible. It says escape_javascript(). That's not helpful for me. Similarly, there isn't much clear guidance online. I've searched for hours.
Here are the relevant parts of my code:
Users#edit.html.erb
<%= render :partial => 'season', :collection => #user.seasons %>
Users#_season.html.erb
<% fields_for prefix, season do |season_form| -%>
<%= error_messages_for :season, :object => season %>
Product: <%= season_form.collection_select :product_id, Product.find(:all, :order =>'name'), :id, :name, {:prompt => "Select Product"}, {:onchange => "collectionSelected(this);"} %>
<% varieties = season.product ? season.product.varieties : Variety.all %>
<%= season_form.select :variety_id, options_from_collection_for_select(varieties, :id, :name, season.variety_id), :prompt => "This is optional" %>
Javascripts#dynamic_varieties.js.erb
var varieties = new Array();
<% for variety in #varieties -%>
varieties.push (new Array (<%=h variety.product_id %>, "<%=h variety.name %>", <%=h variety.id %>));
<% end -%>
function collectionSelected(e) {
product_id = e.getValue();
options = e.next(1).options;
options.length = 1;
varieties.each(function(variety) {
if (variety[0] == product_id) {
options[options.length] = new Option(variety[1], variety[2]);
}
});
}
Assuming you're just doing some escaping wrong (and that rails does it correctly), you could try something like:
var varieties = <%= #varieties.map { |v| [v.product_id, h(v.name), v.id] }.to_json %>

Dynamically Generated Select Menus Not Holding State in Edit View

I'm following Railscast 88 to create a dynamic dependent dropdown menu. http://railscasts.com/episodes/88-dynamic-select-menus
I'm rendering these dropdowns inside a partial that I'm using in a multi-model form. The form I'm using follows the Advanced Rails Recipes process by Ryan Bates. Because I'm rendering the dropdown inside a partial, I had to depart from strictly following the Railscast code. On the Railscast link provided above, comments 30-31 and 60-62 address these issues and provide an approach that I used.
For new records, everything is working great. I select a parent object from the dropdown, and the Javascript dynamically limits the child options to only those items that are associated with the parent I selected. I'm able to save my selections and everything works great.
The problem is that when I go back to the edit page, and I click on the child selection dropdown, the constraints tying it to the parent object are no longer in place. I'm now able to select any child, whether or not it's connected to the parent. This is a major user experience issue because the list of child objects is just too long and complicated. I need the child options to always depend on the parent that is selected.
Here's my code:
Controller#javascripts
def dynamic_varieties
#varieties = Variety.find(:all)
respond_to do |format|
format.js
end
end
Views#javascripts #dynamic_varieties.js.erb
var varieties = new Array();
<% for variety in #varieties -%>
varieties.push(new Array(<%= variety.product_id %>, '<%=h variety.name %>', <%= variety.id %>));
<% end -%>
function collectionSelected(e) {
product_id = e.getValue();
options = e.next(1).options;
options.length = 1;
varieties.each(function(variety) {
if (variety[0] == product_id) {
options[options.length] = new Option(variety[1], variety[2]);
}
});
}
Views#users #edit.html.erb
<% javascript 'dynamic_varieties' %>
<%= render :partial => 'form' %>
View#users #_form.html.erb
<%= add_season_link "+ Add another product" %>
<%= render :partial => 'season', :collection => #user.seasons %>
view#users #_season.html.erb
<div class="season">
<% new_or_existing = season.new_record? ? 'new' : 'existing' %>
<% prefix = "user[#{new_or_existing}_season_attributes][]" %>
<% fields_for prefix, season do |season_form| -%>
<%= error_messages_for :season, :object => season %>
<div class="each">
<p class="drop">
<label for = "user_product_id">Product:</label> <%= season_form.collection_select :product_id, Product.find(:all), :id, :name, {:prompt => "Select Product"}, {:onchange => "collectionSelected(this);"} %>
<label for="user_variety_id">Variety:</label>
<%= season_form.collection_select :variety_id, Variety.find(:all), :id, :name, :prompt => "Select Variety" %>
</p>
<p class="removeMarket">
<%= link_to_function "- Remove Product", "if(confirm('Are you sure you want to delete this product?')) $(this).up('.season').remove()" %>
</p>
</div>
<% end -%>
Here's your culprit:
<%= season_form.collection_select :variety_id, Variety.find(:all),
:id, :name, :prompt => "Select Variety" %>
Works perfectly on a new record because it's showing everything, and gets overwritten when the select changes on the other select box.
You need to do something like this:
<% varieties = season.product ? season.product.varieties : Variety.all %>
<%= season_form.select :variety_id,
options_from_collection_for_select(varieties, :id,
:name, season.variety_id), :prompt => "Select Variety" %>
Which will use only the Varieties linked to season.product. If season.product doesn't exist it lists all of them. It will also automatically select the right one if the existing record had a variety_id.
It also wouldn't hurt to change.
<%= season_form.collection_select :product_id, Product.find(:all),
:id, :name, {:prompt => "Select Product"},
{:onchange => "collectionSelected(this);"} %>
to
<%= season_form.select :product_id,
options_from_collection_for_select(Product.find(:all),
:id, :name, season.product), {:prompt => "Select Product"},
{:onchange => "collectionSelected(this);"} %>
Which will select the proper product on page load. This second part is essentially the Rails way of doing what BYK's first suggestion was. However, given the nature of the onchange method given to the select box, this line on its own would not solve the problem. It would just enhance the user experience by highlighting the product associated with the season.
I think you have two options:
Give one of the products(or simply the first element of the product list) a "selected" attribute which will force the browser to select that one always.
Trigger the "collectionSelected" function on "dom ready" or "window.onload" with giving the product list selectbox as its parameter.
And a note: never, ever trust JavaScript to force the user to send proper data to the server.

Categories