How can I send the select box value to javascript in rails - ruby-on-rails

I got the following code, which I want when people choose the OPTIONS, then show the Add an option button
<%= f.fields_for :questions do |question_form| %>
<%= question_form.text_field :question_text %>
<%= question_form.select :question_type, [ 'TEXT', 'OPTIONS', 'UPLOAD' ], :prompt => 'Select One', :id => "my_id", :onchange => "myFunction()" %>
<%= question_form.link_to_remove "Remove this Question" %>
<%= question_form.fields_for :options do |option_form| %>
<%= option_form.text_field :option_text %>
<%= option_form.link_to_remove "Remove this option" %>
<% end %>
<p id = "test" hidden><%= question_form.link_to_add "Add a option", :options %></p>
<script>
function myFunction(){
var x = document.getElementById("my_id").value;
if (x == "OPTIONS") {
document.getElementById("test").hidden = false;
}
}
</script>
<% end %>

First of all, you can't send a value from Rails to Js during Js execution. In that moment you are already in the browser context unless you ask something via Ajax to your server.
In this case everything can and has to be done in your browser context. Just change this line:
var x = document.getElementById("my_id").value
For:
var e = document.getElementById("my_id");
var x = e.options[e.selectedIndex].value;
This should do the trick.

Related

Using Simple_Form for Searching - Undefined Method

I'm attempting to a create a simple form that allows me to run a new search on the existing 'results' page using simple form.
The exact same code works fine when performing the search from another (landing) page. However, when I try to insert it into the results page I'm getting
undefined method 'vtype' for #
<Venue::ActiveRecord_Relation:0x007fd6860eb730>
vtype is both a table column and also the name of the param i'm passing to search on.
The simple_form looks like this:
<%= simple_form_for :results, html: { class: "form-inline justify-content-center" } do |f| %>
<%= f.error_notification %>
<%= f.select :vtype, options_for_select([['Happy Hours Anywhere','Anywhere'],['After Work Drinks','After Work Drinks'],['Somewhere to Relax with Friends', 'Relaxing with Friends'], ['A Club Night','Club Night'], ['Somewhere for Date Night','Date Night'], ['A Place to Watch Sports', 'Watching Sports']]),{} ,:class => "form-control select-box font-lightweight" %>
starting
<%= f.select :date, options_for_select(dates_for_search_select.each_with_index.map{|d, i| [d[1],d[0]]}), {}, :class => "form-control select-box font-lightweight" %>
at
<%= f.select :time, options_for_select(times_for_search_select.each_with_index.map{|d, i| [d[1],d[0]]}), {}, :class => "form-control select-box font-lightweight" %>
</h4>
<%= f.button :submit, 'Discover', :class => 'btn btn-block btn-danger btn-embossed top-margin ' %>
<%end%>
My controller looks like this:
def results
if params.has_key?(:results)
##results = Venue.joins(:offers).where("offers.offertype = '2-4-1'")
#finddate = (params[:results][:date]).to_date
#findtime = (params[:results][:time]).to_time
#resultsdate = DateTime.new(#finddate.year,#finddate.month,#finddate.day,#findtime.hour)
#results = Venue.joins(:offers).where(["venues.vtype = ? and offers.start >= ?", params[:results][:vtype], #resultsdate])
else
#results = Venue.joins(:offers).where(["offers.start = ?", Date.today])
end
end
What's wrong with this form running on the 'results' page?

Multiple saves with one submit

I need a form that includes 1 radio button, 1 submit button and a checkbox for each listed item.
Upon submit, the form should save a separate record for each checked item. Each saved item should include the value of the radio button along with other hidden values.
The form renders but crashes upon submit. The error message is:
undefined method `permit' for #<Array:0x007fb4b3b1a520>
My code is:
<%= form_tag(controller: "handoffs", action: "create", method: "post") %>
<%= radio_button_tag(:attend, "arrive") %>
<%= label(:handoff_arrive, "drop-off") %>
<%= radio_button_tag(:attend, "depart") %>
<%= label(:handoff_depart, "pick-up") %>
<% #parent.children.each do |child| %>
<%= check_box_tag "handoff[][check]" %>
<strong>
<%= child.fname %>
<%= child.mname %>
<%= child.lname %>
</strong><br>
<% group = Group.find(child.group_id) %>
<%= hidden_field_tag "handoff[][attend]" %>
<%= hidden_field_tag "handoff[][group_name]", :value => group.name %>
<%= hidden_field_tag "handoff[][child_id]", :value => child.id %>
<%= hidden_field_tag "handoff[][center_id]", :value => #center.id %>
<%= hidden_field_tag "handoff[][escort_fname]", :value => #parent.fname %>
<%= hidden_field_tag "handoff[][escort_lname]", :value => #parent.lname %>
<%= hidden_field_tag "handoff[][child_fname]", :value => child.fname %>
<%= hidden_field_tag "handoff[][child_mname]", :value => child.mname %>
<%= hidden_field_tag "handoff[][child_lname]", :value => child.lname %>
<% end %>
<%= button_to :submit, :class => 'f_submit' %>
<% end %>
Controller actions:
def new
#handoff = Handoff.new
#parent = current_parent
#center = Center.find(#parent.center_id)
end
def create
params["handoff"].each do |handoff|
if params[:handoff["check"]] != ""
#handoff = Handoff.new(handoff_params)
#handoff.save
end
end
end
def handoff_params
params.require(:handoff).permit(:attend, :group_name, :child_id, :center_id, :escort_fname, :escort_lname, :child_fname, :child_mname, :child_lname)
end
Request parameters (in error report)
{"utf8"=>"✓",
"authenticity_token"=>"snqrS130bXNV4bmMHOMlXeyhX2rWFVpmY/PYIv0jn97MBOLSWWw2jBbeYGPyjt7O9l5pRVNuFiu1qOwkGpELTA==",
"attend"=>"depart", "handoff"=>[{"check"=>"1", "attend"=>"",
"group_name"=>"{:value=>\"Gifted\"}", "child_id"=>"{:value=>60}",
"center_id"=>"{:value=>4}", "escort_fname"=>"{:value=>\"Richard\"}",
"escort_lname"=>"{:value=>\"Messing\"}",
"child_fname"=>"{:value=>\"Aaron\"}",
"child_mname"=>"{:value=>\"Lawrence\"}",
"child_lname"=>"{:value=>\"Schwartz\"}"}, {"check"=>"1", "attend"=>"",
"group_name"=>"{:value=>\"Arts & Crafts\"}",
"child_id"=>"{:value=>61}", "center_id"=>"{:value=>4}",
"escort_fname"=>"{:value=>\"Richard\"}",
"escort_lname"=>"{:value=>\"Messing\"}",
"child_fname"=>"{:value=>\"Joseph\"}",
"child_mname"=>"{:value=>\"Michael\"}",
"child_lname"=>"{:value=>\"Messing\"}"}], "method"=>"post",
"controller"=>"handoffs", "action"=>"create"}
I had similar case. First you need to create array with all values that you would like to export I used helper to do that. I'll show you my example:
def get_table_of_keywords(keywords)
exact_keywords = []
keyword_array.each do |key|
if !key.blank?
exact_keywords << {keyword: key, created_at: DateTime.now.in_time_zone, updated_at: DateTime.now.in_time_zone }
end
end
exact_keywords
end
And the you are using create:
#inserted_keywords = #campaign.keywords.create(get_table_of_keywords(params[:keyword][:keyword])) # add new keywords to the list

Search filter applied through "link_to"

So i have a search filter working perfectly in my index view. The code in the controller is as follows
def index
#tutor = Tutor.where(:admin => false)
#tutor_array = []
#tutor_array << #tutor.fees_search(params[:fees_search]) if params[:fees_search].present?
#tutor_array << #tutor.subject_search(params[:subject_search]) if params[:subject_search].present?
#tutor_array << #tutor.lssubject_search(params[:lssubject_search]) if params[:lssubject_search].present?
#tutor_array << #tutor.ussubject_search(params[:ussubject_search]) if params[:ussubject_search].present?
#tutor_array << #tutor.jcsubject_search(params[:jcsubject_search]) if params[:jcsubject_search].present?
#tutor_array.each do |tutor|
ids = #tutor.merge(tutor).map(&:id)
#tutor = Tutor.where(id: ids)
end
#tutor = #tutor.sort_by { |tutor| tutor.rating.rating }.reverse
#tutor = #tutor.paginate(:page => params[:page], :per_page => 2)
end
And in my view the form that passes in the search filters for me is
<form class='form-inline'>
<%= form_tag(tutors_path, method: :get) do %>
<div class='row', id='filter-form'>
<div class='form-group'>
<%= label_tag 'subject_search', 'Primary Subject' %>
<% subject_array = Subject.all.map { |subject| [subject.name] } %>
<%= select_tag 'subject_search', options_for_select(subject_array, :selected => params[:subject_search]), :include_blank => true, class:'form-control' %>
<%= label_tag 'lssubject_search', 'Lower Sec Subject' %>
<% lssubject_array = Lssubject.all.map { |lssubject| [lssubject.name] } %>
<%= select_tag 'lssubject_search', options_for_select(lssubject_array, :selected => params[:lssubject_search]), :include_blank => true, class:'form-control' %>
<%= label_tag 'ussubject_search', 'Upper Sec Subject' %>
<% ussubject_array = Ussubject.all.map { |ussubject| [ussubject.name] } %>
<%= select_tag 'ussubject_search', options_for_select(ussubject_array, :selected => params[:ussubject_search]), :include_blank => true, class:'form-control' %>
</div>
</div>
<div class='row', id='filter-form2'>
<div class='form-group'>
<%= label_tag 'jcsubject_search', 'JC Subject' %>
<% jcsubject_array = Jcsubject.all.map { |jcsubject| [jcsubject.name] } %>
<%= select_tag 'jcsubject_search', options_for_select(jcsubject_array, :selected => params[:jcsubject_search]), :include_blank => true, class:'form-control' %>
<%= label_tag 'fees_search', 'Max Fees' %>
<%= select_tag 'fees_search', options_for_select((10..150).step(10), :selected => params[:fees_search]), :include_blank => true, class:'form-control' %>
<%= submit_tag 'Filter', class: 'btn btn-primary btn-xs' %>
</div>
</div>
<% end %>
<div id='filter-reset'>
<%= link_to 'Reset Filters', tutors_path, class: 'btn btn-primary btn-xs' %>
</div>
</form>
And when a filter is passed in an example or the URL attained is as follows
/tutors?utf8=✓&subject_search=Science&lssubject_search=&ussubject_search=&jcsubject_search=&fees_search=&commit=Filter
What i would like to ask is, how do i pass in the filters through a button?
So if i were to click on "Math" or "English" its equivalent to passing in the filter through the form? I understand that it'll most likely be link_to tutors_path(???) but what should go into the parenthesis to pass the correct filters in?
I tried <%= link_to subs.name, tutors_path(:subject_search => subs.name %> and it seems like it works. To provide some context here's the view and how subs.name comes about.
<% tutor.subjects.each do |subs| %>
<span class='badge'id='tutor-listing-badge'>
<%= link_to subs.name, tutors_path(:subject_search => subs.name) %>
</span>
<% end %>

Rails - How to assign a value to a form through a script and reload it with the assigned value?

For my rails application, I have a form that saves "content" in my model when submitted. How do I modify my script below and use "Sessions" so that "onSuccess(event)", I assign the contents of the alert as a temporary value to :content and my page reloads/refreshes with the content of the alert inside the text_area?
<%= form_for([#project, #project.blogs.build]) do |f| %>
<div class="field">
<%= f.text_area :content, label: "Blog", :class => "redactor" %>
</div>
<%= f.submit "Submit" %>
<% end %>
<script>
...
function onSuccess(event) {
alert('NICE! ' + event.data.Id + ' was added.');
}
...
</script>
if you use redactor.js.
function onSuccess(event) {
$('.redactor').redactor('insertText', 'NICE! ' + event.data.Id + ' was added.');
}
There are an option with ajax
<%= form_for [#project, #project.blogs.build], :remote => true, :html => { :id => "ajax_form" } do |f| %>
<div class="field">
<%= f.text_area :content, label: "Blog", :class => "redactor", :id => "change_me" %>
</div>
<%= f.submit "Submit" %>
<% end %>
<script>
$(function() {
$("#ajax_form").bind('ajax:success', function(data, status, xhr) {
$("#change_me").val("changed");
}).bind('ajax:error', function(xhr, status, error) {
console.log(error);
console.log(status);
});
});
</script>

Sorting nested form fields in rails

I'm trying to create an inventory form that sorts the products based on their category. Ideally I'll be able to have these products listed by category, and will put in some javascript to hide/show products of a given category.
Currently, I'm having trouble wrapping my head around how to split my products up by category in my form. Here's what I currently have (modeled after Ryan Bates' Railscasts for nested attributes):
class InventoriesController < ApplicationController
def new
#title = "Take Inventory"
#vendor = ProductVendor.find(params[:product_vendor_id])
#inventory = Inventory.new()
#products = #vendor.products.active
#products.each do |product|
#inventory_line_item = #inventory.inventory_line_items.build({:product_id => product.id})
end
end
My form for a new inventory:
<%= form_for #inventory do |f| %>
<table>
<tr>
<th>Item</th>
<th>Quantity</th>
</tr>
<% f.fields_for :inventory_line_items do |builder| %>
<tr>
<td><%= builder.object.product.name %></td>
<td><%= builder.text_field(:quantity, :size => 3) %></td>
<%= builder.hidden_field :product_id %>
</tr>
<% end %>
</table>
<%= f.hidden_field(:user_id, :value => current_user.id) %>
<%= f.hidden_field(:location_id, :value => current_location.id) %>
<%= f.hidden_field(:product_vendor_id, :value => #vendor.id) %>
<%= f.submit "Submit" %>
<% end %>
So I have another model called product_category that has_many products. How do I sort and separate my products by category in the controller and form? Also, is there a way to do this using Formtastic? Thanks!
It's actually pretty simple to implement. Add a hidden field in the nest_form field with the attribute position (add this attr to your model of course) and add this to your js along with using the jquery-ui.js
$('#task_fields').sortable({
items: '.fields',
dropOnEmpty: true,
cursor: 'move',
handle: '.move',
opacity: 0.4,
scroll: true,
axis:'y',
placeholder: 'ui-state-highlight',
start: function(e, ui) {
ui.placeholder.height(ui.item.height());
},
update: function() {
$(this).children(".fields").each(function(index) {
$(this).children('input.task_position').val(index + 1);
});
}
});
here's what I have in my _form.html.haml
= f.fields_for :tasks do |t|
= t.text_field :name
= t.hidden_field :position, :class => :task_position
= t.collection_select :account_id, Account.all, :id, :full_name, :prompt => 'Assign task to...'
.button-group
%span{:class => "button icon no-text move pill"}
= t.link_to_remove "", :class => "button icon no-text remove pill"
= f.link_to_add "Add a Task", :tasks, :class => "button icon add"
This worked really well.

Resources