How do I combined the day and time into a "start_time" variable (and "end_time") before submitting? JS?
<%= form_for #task do |f| %>
<%= render 'shared/error_messages', object: f.object %>
<div class="time_selectors">
<%= f.label :start_time %>
<%= f.text_field :start_time, :class => 'datepicker' %>
<select class="form-control time_dropdown" id="start_hour">
<option>Select Date</option>
</select>
<div class="clear_both"></div>
<%= f.label :end_time %>
<%= f.text_field :end_time, :class => 'datepicker' %>
<select class="form-control time_dropdown" id="end_hour">
<option>Select Date</option>
</select>
</div>
<div class="clear_both"></div>
</div>
<div class="clear_both"></div>
<%= f.submit "Create Task", class: "btn btn-large btn-primary" %>
</div>
<% end %>
I have them combined in my Task model, and I'd prefer to leave them combined if I can.
My JS right now doesn't work. What am I missing?
$('#new-task').submit ()->
valuesToSubmit = $(this).serialize
console.log('test')
console.log(valuesToSubmit)
return false
$('button').click ()->
console.log ('test2')
What about something like this?
$('form').on 'submit', (event) ->
event.preventDefault()
start_time = ''
start_time += $(#).find('input[name=start_day]').val()
start_time += '_'
start_time += $(#).find('input[name=start_hour]').val()
$('<input/>', {type: 'hidden', name: 'start_time', value: start_time}).appendTo($(#))
#submit()
(*The CoffeeScript version hasn't been tested - use the working Fiddle as your guide.)
Fiddle
Related
I am still unable to solve this problem and i would be really grateful if anyone can help me. I have already successfully coded a product ordering form which will GET price of specific products from the products_table. My form layout is as:
new.html.erb
<h1>Add a new order for <%= #customer.name %></h1>
<div class="row">
<%= form_for(#order) do |f| %>
.
.
.
.
<h3>Order Details</h3>
<%= f.label :address_id, "Delivery Address" %>
<%= f.collection_select :address_id, #addresses, :id, :select_address, {:prompt => "Select delivery location"}, {:class => "form-control"} %></br>
<%= f.label :del_date, "Delivery Date" %>
<%= f.date_select :del_date, {:class => "form-control"} %></br>
<%= f.label :owner_id, "Person-In-Charge" %>
<%= f.collection_select :owner_id, #owners, :id, :name, {:prompt => "Who ordered?"}, {:class => "form-control"} %>
<%= f.label :telephone %>
<%= f.text_field :telephone, class: 'form-control' %>
<%= f.label :remark, "Order Remark" %>
<%= f.text_area :remark, class: 'form-control' %>
<%= f.label :t_price, "Total Amount" %>
<%= f.text_field :t_price, class: 'form-control' %></br>
<h3>What items would you like to place?</h3>
<%= f.add_nested_fields_link :single_orders, "Add Product" %>
<%= f.nested_fields_for :single_orders do |builder| %>
<div class = "form-inline">
<%= builder.collection_select :product_id, #products, :id, :select_product, {:prompt => "choose product"}, {:class => "product_selection form-control"} %>
<%= builder.text_field :ctn_price, placeholder: "Price/carton", readonly: true, class: 'ctn_price_field form-control' %>
<%= builder.text_field :qty, placeholder: "Quantity",id: "quantity", class: 'form-control' %>
<%= builder.text_field :price, placeholder: "Amount", id: "amount", readonly: true, class: 'form-control' %>
<%= builder.remove_nested_fields_link %>
</div>
<% end %>
<%= f.submit "place order", class: "btn btn-primary" %>
</div>
<% end %>
</div>
when the product is selected via collect_select, the order.js.coffee will run:
order.js.coffee
jQuery ->
$(".product_selection").on "change", ->
$.ajax
url: "/orders/get_product_prices"
type: "GET"
dataType: "script"
data:
product_id: $('.product_selection option:selected').val()
which will route to:
resources :orders, only: [:index, :new, :edit, :create, :update, :inactive, :active, :destroy] do
member do
post :create, :inactive, :active
end
collection do
get 'get_product_prices', to: "orders#get_product_prices"
end
end
which is run the file get_product_prices.js.erb
/* global $ */
$('.ctn_price_field').each(function(){
$(this).val(<%= #product.price %>)
});
The problem i am facing is that this codes only works for the first product element in the form. As I want this form to able to accept multiple products via the nested_field:single_order when i generate 3 of the same nested_fields via orders_controller.rb:
def new
#order = Order.new
#customer = Customer.find(params[:id])
#addresses = Address.where(customer_id: #customer.id)
#owners = Owner.where(customer_id: #customer.id)
#promotions = Promotion.where(status: "active")
#packages = Package.all
#products = Product.where(status: "active")
#package_products = PackageProduct.all
3.times do
#order.single_orders.build
end
end
def get_product_prices
#product = Product.find_by(id: params[:product_id])
end
This is the HTML codes when i inspect the element on chrome
<fieldset class="nested_fields nested_order_single_orders">
<div class="form-inline">
<select class="product_selection form-control" name="order[single_orders_attributes][0][product_id]" id="order_single_orders_attributes_0_product_id"><option value="">choose product</option>
<option value="2">Apple</option>
<option value="3">Orange</option>
<option value="4">Pear</option>
<option value="5">Watermelon</option>
<option value="6">Avocado</option>
<option value="7">Kiwi</option></select>
<input placeholder="Price/carton" readonly="readonly" class="ctn_price_field form-control" type="text" name="order[single_orders_attributes][0][ctn_price]" id="order_single_orders_attributes_0_ctn_price">
<input placeholder="Quantity" id="quantity" class="form-control" type="text" name="order[single_orders_attributes][0][qty]">
<input placeholder="Amount" id="amount" readonly="readonly" class="form-control" type="text" name="order[single_orders_attributes][0][price]">
<a class=" remove_nested_fields_link" data-delete-association-field-name="order[single_orders_attributes][0][_destroy]" data-object-class="single_order" href="">x</a>
</div>
</fieldset>
the other 2 ctn_price_field will duplicate the prices of whichever product is selected on the first nested_field element. Can anybody show where have i gone wrong with this codes? does the problem arise from my jQuery codes or my rails? thank you for any help provided..
In an attempt to make my rails html more readable I extracted several parts of it into partials. I then use jquery to render the partials. The issue is that now the form has come all "unhooked" so to speak, meaning when I attempt to submit the form it acts as though the partials don't exist. I suspect I am not understanding quite how forms work, because it seems like in other answers related to this the form builder isn't even addressed.
This SO question seems related to what I want to do but I think I'm too inexperienced to grasp it properly
The code I have thus far goes as follows:
/assets/javascripts/work_order.js
$(document).ready(function(){
$('.best_in_place').best_in_place();
$('#work_order_dueDate').datepicker();
$.datepicker.setDefaults({ dateFormat: 'dd-mm-yy'});
var selection_made = false
$('#work_order_project_type_id').change(function(){
if (!selection_made){
selection_made = true
var selection = $(this).find('option:selected').text();
if (selection == "Variable Data Mailing"){
$.get('/presort_informations/new');
$.get('/printing_instructions/new');
}
else if (selection == "Mailing"){
$.get('/presort_informations/new');
}
else if (selection == "Print Job"){
$.get('/printing_instructions/new');
}
}
});
});
and then
/views/work_orders/_form.html.erb
<%= form_for(#workorder) do |f| %>
<% if #workorder.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#workorder.errors.count, "error") %> prohibited this workorder from being saved:</h2>
<ul>
<% #workorder.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<fieldset class="general-info">
<legend>General</legend>
<div class="col-md-12">
<div class="col-md-3">
<div class="form-group">
<%= f.label :Job_Title, class: "control-label" %>
<%= f.text_field :title, class:"form-control" %>
</div>
<div class="form-group">
<%= f.label :Project_Type, class: "control-label" %>
<%= f.collection_select(:project_type_id, ProjectType.all, :id, :name, {:prompt => true}, {:class => "form-control"}) %>
</div>
</div>
<div class="col-md-3">
<div class="form-group">
<%= f.label :Rep, class: "control-label" %>
<%= f.text_field :rep, class:"form-control" %>
</div>
<div class="form-group">
<%= f.label :Labels, class: "control-label" %>
<%= f.collection_select(:labels_id, Labels.all, :id, :name, {:prompt => true}, {:class => "form-control"}) %>
</div>
</div>
<div class="col-md-3">
<div class= "form-group">
<%= f.label :Due_Date, class: "control-label" %>
<%= f.text_field :dueDate, class: "form-control" %>
</div>
<div class="form-group">
<%= f.label :Project_Description, class: "control-label" %>
<%= f.text_area :projectDescription, class: "form-control" %>
</div>
</div>
</div>
</fieldset>
<fieldset class="presort-information">
</fieldset>
<div class="col-md-6 printing">
</div>
<fieldset class="production-details">
<legend>Production</legend>
<%= f.fields_for :production_details, ProductionDetails.new do |ff| %>
<%end%>
</fieldset>
<%= f.hidden_field(:number, :value => #workorder.number) %>
<%= f.hidden_field(:client_id, :value => #workorder.client_id) %>
<%= f.submit(class: "btn btn-default") %>
<% end %>
and as an example of one of the partials:
/app/views/presort_informations/new.js.erb
$('.presort-information').append( '<%= j render("presort_informations/form") %>' );
/app/views/presort_informations/_form.html.erb
<legend>Mailing</legend>
<%= fields_for :presort_information, PresortInformation.new do |ff| %>
.
.
.
<% end %>
I'm not really sure how to tie this all together so that I can load the partials based on the select box, but then submit them all as one form.
Edit:
I found this SO question which deals with the same issue, but I suspect that because I am rendering the partial after the page has been loaded I no longer have access to the form builder variable.
$('.presort-information').append( '<%= j render("presort_informations/form", f: f) %>' );
gives an undefined variable error when it's called. I'm still not sure how to bridge this gap between jquery and rails.
Turns out it was a relatively (if new conceptually to me) easy fix
First, load each DOM partial in along with hidden sections.
<%= form_for(#workorder) do |f| %>
<% if #workorder.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#workorder.errors.count, "error") %> prohibited this workorder from being saved:</h2>
<ul>
<% #workorder.errors.full_messages.each do |message| %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<fieldset id="general-info-partial">
<%=render("genInfo", f: f)%>
</fieldset>
<fieldset id="presort-information-partial">
<%=render("presort_informations/form", f: f)%>
</fieldset>
<div class="col-md-6">
<fieldset id="printing-information-partial">
<%=render("printing_instructions/form", f: f)%>
</fieldset>
</div>
<fieldset id="production-details-partial">
<%=render("production_details/form", f: f) %>
</fieldset>
<%= f.hidden_field(:number, :value => #workorder.number) %>
<%= f.hidden_field(:client_id, :value => #workorder.client_id) %>
<input type="submit" value="Submit" class="btn btn-default">
<% end %>
<div id="hidden-general-info" class="hidden"></div>
<div id="hidden-presort-information" class="hidden"></div>
<div id="hidden-printing-information" class="hidden"></div>
Then the Javascript to move things in and out of the form:
$(document).ready(function(){
$('.best_in_place').best_in_place();
$('#work_order_dueDate').datepicker();
$.datepicker.setDefaults({ dateFormat: 'dd-mm-yy'});
var presortFields = $('#presort-information-partial');
var printingFields = $('#printing-information-partial');
var presortHidden = $('#hidden-presort-information');
var printingHidden = $('#hidden-printing-information');
presortHidden.html(presortFields.html());
presortFields.html('');
printingHidden.html(printingFields.html());
printingFields.html('');
$('#work_order_project_type_id').change(function(){
var selection = $(this).find('option:selected').text();
if (selection == "Variable Data Mailing"){
if (printingFields.html() == '' && presortFields.html() == ''){
printingFields.html(printingHidden.html()).hide().slideDown();
presortFields.html(presortHidden.html()).hide().slideDown();
}
else if(printingFields.html() == '' && !(presortFields.html() == '')){
printingFields.html(printingHidden.html()).hide().slideDown();
}
else if(!(printingFields.html() == '') && presortFields.html() == ''){
presortFields.html(presortHidden.html()).hide().slideDown();
}
}
else if (selection == "Mailing"){
if(!(printingFields.html() == '')){
printingFields.slideUp();
printingFields.html('');
presortFields.html(presortHidden.html()).hide().slideDown();
}else{
presortFields.html(presortHidden.html()).hide().slideDown();
}
}
else if (selection == "Print Job"){
printingFields.html(printingHidden.html()).hide().slideDown();
presortFields.slideUp();
presortFields.html('');
}
});
Basically, the idea was to load everything in as if I was going to use it all, and then just move the partials into a hidden section of the DOM, and then use JS to put them back in when the user makes a selection
I am using simple_form for my form, and would love to enable some basic JS character count on a text field.
My form partial looks like this:
<%= simple_form_for(#post, html: {class: 'form-horizontal' }) do |f| %>
<%= f.error_notification %>
<%= f.input_field :parent_id, as: :hidden %>
<div class="field">
<% if can? :manage, #post %>
<%= f.input_field :status, label: "Status", collection: Post.statuses.keys, selected: :unconfirmed %>
<% end %>
</div>
<%= f.input :title, placeholder: "Enter Title" %>
<%= f.input :photo %>
<%= f.input :file %>
<%= f.input :body %>
<div class="report-submit">
<%= f.button :submit %>
</div>
<% end %>
How do I go about doing this?
Assign an id to the text field, then add a span beside it where you will show the counter, assign an id to the span as well.
<%= f.input :body, id: "body-field" %>
<span id="body-count">0 characters</span>
In Javascript add this code
$("#body-field").on("keyup", function(){
length = $(this).val().length;
$("#body-count").html(length);
});
I have created a fiddle to show how it works, click here http://jsfiddle.net/L99c30qh/
I want to pass the selected value from the drop down to fullcalendar plugin and the rails form
The select tag
<%= form_tag appointments_path, :html => {:id => "form-1"} do %>
<%= select_tag(:worker_id, options_from_collection_for_select(#client.workers, :id, :name), :selected => #a, :style=>"width:170px;", :prompt => "Select Staff Member")%>
<% end %>
I am passing the #a variable by ajax to
<script>
$('#worker_id').change(function (e) {
var a = parseInt($(this).val());
alert(a);
$.ajax({
type: "GET",
url:"/customers/new",
data : { id: a },
success:function(result){
$('#content1').html("<%= escape_javascript(render :partial =>'form', :locals => ????) %>");
}
});
$('#calendar').fullCalendar('destroy');
RenderCalendar($(this).val());
});
</script>
I am not sure whether i am doing it in right way. I want to pass the value in form which is here:
<%= form_for(#customer) do |f| %>
<%#= f.error_notification %>
<div class="field">
<%#= f.label :Service_Name %>
<%#= f.collection_select :service_id, Category.where(:client_id => #client).order(:name), :services, :name, :id, :service_name %>
</div>
<br /> <br />
<%= f.fields_for :appointments do |builder|%>
<fieldset>
<% if #a!=0 %>
<%= builder.hidden_field :worker_id, :value=> #customer.worker_id %>
<%= builder.hidden_field :client_id, :value=> #client.id%>
<%= builder.label :price %>
<%= builder.text_field :price %>
<%= builder.label :Service_Name %>
<%= builder.collection_select(:service_id, #a.order(:service_name), :id, :service_name, :include_blank => true, :multiple => true ) %>
<% end %>
<%= builder.label :appointment_date %>
<%= builder.date_select :appointment_date %> <br />
<%= builder.label :appointment_start_time %>
<%= builder.time_select :appointment_start_time, ampm: true %> <br />
<%= builder.label :appointment_end_time %>
<%= builder.time_select :appointment_end_time, ampm: true %>
</fieldset>
<%end%>
<div class="field">
<%= f.label :title %>
<%= f.text_field :title %>
</div>
<div class="field">
<%= f.hidden_field :worker_id, :value=>#customer.worker_id %>
</div>
<div class="form-actions">
<%= f.button :submit, :class=>"btn btn-primary" %>
</div>
<% end %>
If I understand correctly: you are trying to rerender the fullcalender jquery plugin with your ajax success callback based on the user selected from the select tag here:
<%= form_tag appointments_path, :html => {:id => "form-1"} do %>
<%= select_tag(:worker_id, options_from_collection_for_select(#client.workers, :id, :name), :selected => #a, :style=>"width:170px;", :prompt => "Select Staff Member") %>
<% end %>
There is an inherent issue with the way you're trying to do this. Any embedded ruby in your views will run only once at runtime. Essentially, your escape_javascript(render partial..... will not run because any embedded ruby is done running at that point.
What you could do is keep the ajax call you already have but run the render partial code in your '/customers/new', instead of trying to call it in the ajax callback -which is after runtime
render :partial =>'form', :locals => ????
This will return the partial code with which you want to then place on the page. With your ajax, simply place it on the page something like this:
success:function(result){
$('#content1').html(result);
}
I have a javascript file for the cascading dropdown boxes loading from different models. But I dont know how to include into the dropdown list.
Form:
<% content_for :javascript do %>
var master_surveys = <%=
Condition::MasterSurvey.all.map {|ms| {id: ms.Master_Survey_Code, to_s: ms[:Master_Survey_Name]}}.to_json.html_safe
%>
var elements = <%= elements = Hash.new { |hash, code| hash[code] = [] }
Condition::Element.all.each {|e| elements[e.Master_Survey_Code] << {id: e.Element_Code, to_s: e.Element} }.to_json.html_safe
%>
var sub_elements = <%= sub_elements = Hash.new { |hash, code| hash[code] = [] }
Condition::SubElement.all.each {|s| sub_elements[s.Element_Code] << {id: s.Sub_Element_Code, to_s: s.Sub_Element} }.to_json.html_safe
%>
var materials = <%=
materials = Hash.new { |hash, code| hash[code] = [] }
Condition::RenewSchedule.all.each {|rs| materials[rs.Sub_Element_Code] << {id: rs.Material_Code, to_s: rs.Material} }.to_json.html_safe
%>
$(document).ready(function(){
$('select#enr_rds_surv_rdsap_xref_master_survey').chainedTo('select#enr_rds_surv_rdsap_xref_Element_Code');
});
<% end %>
<%= form_for(#enr_rds_surv_rdsap_xref) do |f| %>
<% if #enr_rds_surv_rdsap_xref.errors.any? %>
<div id="error_explanation">
<h2><%= pluralize(#enr_rds_surv_rdsap_xref.errors.count, "error") %>:</h2>
<ul>
<% #enr_rds_surv_rdsap_xref.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
<% end %>
<div class="field">
<%= f.label :Master_Survey %><br/>
<%= f.select :master_survey, Condition::MasterSurvey.all.map{|e| [e.Master_Survey_Code]}, { :prompt => 'Please Select' } %>
</div>
<div class="field">
<%= f.label :Element_Code %><br/>
<%= f.select :Element_Code, Condition::Element.all.map{|e| [e.Element, e.Element_Code]}, { :prompt => 'Please Select' } %>
</div>
<div class="field">
<%= f.label :Sub_Element_Code %><br/>
<%= f.select :Sub_Element_Code, Condition::SubElement.all.map{|e| [e.Sub_Element, e.Sub_Element_Code]}, { :prompt => 'Please Select' } %>
</div>
<div class="field">
<%= f.label :Material_Code %><br/>
<%= f.select :Material_Code, Condition::RenewSchedule.all.map{|e| [e.Material]}, { :prompt => 'Please Select' } %>
</div>
<div class="actions">
<%= f.submit 'Save'%>
</div>
<% end %>
So, The above javascript file collect the data from the parent. In the form, I created a dropdown list statically loaded the data from the database. I want to include the javascript to loaded automatically into the dropdown list dynamically.
Thanks in advance!!!!
I usually do it by Ajax and partials(or page, up to you.), not nice but might be help?
Bind change even on your parent selects. like
$("#parent_select").change(function(){
$.ajax({
url: '/parents/'+$(this).val()+'/childs/',
complete: function(data){
$('#children_select').html(data);
}
})
});
And in your child controller render a partial(or page) with only contents of options of selected children. like:
<%children.each do |child|%>
<option value='<%=child.id%>'><%=child.name%></option>
<%end%>