I have a "room type" table full of values, I want to make it so that when a user selects a room type from the collection_select the rest of the form gets updated with that room type's values, I can detect when the selection is changed with javascript through $('#room_roomtype_id').change and which room type was selected through $('#room_roomtype_id :selected').text() but I have no idea, and my hours of searching have been futile, how to then update the other form fields with data from the room type table.
Here is my form code:
<%= form_for #room do |f| %>
<% if #room.errors.any? %>
<div class="error_messages">
<h2>Form is invalid</h2>
<ul>
<% for message in #room.errors.full_messages %>
<li><%= message %></li>
<% end %>
</ul>
</div>
<% end %>
<p id="roomtypes", data-url="<%= url_for :controller => 'rooms', :action => 'roomtypeupdate' %>">
<%= f.label :roomtype_id, "Room type" %><br />
<%= f.collection_select :roomtype_id, Roomtype.order(:name), :id, :name, include_blank: true %>
</p>
<p>
<%= f.label :number, "Room number" %><br />
<%= f.text_field :number %>
</p>
<p>
<%= f.label :maxcap, "Capacity" %><br />
<%= f.number_field :maxcap %>
</p>
<p>
<%= f.label :size, "Size" %><br />
<%= f.number_field :size %>
</p>
<p>
<%= f.label :description, "Description" %><br />
<%= f.text_area :description %>
</p>
<p>
<%= f.label :singlebeds, "Number of single beds" %><br />
<%= f.number_field :singlebeds %>
</p>
<p>
<%= f.label :bathrooms, "Number of bathrooms" %><br />
<%= f.number_field :bathrooms %>
</p>
<br />
<p class="button"><%= f.submit %></p>
<% end %>
Something like this should work:
$('#room_roomtype_id').on('change', function () {
// URL for the sake of example - yours will differ
$.get('/rooms/' + this.value + '.json', function (response) {
// dummy response for the sake of example
response = {
"number": "5A",
"maxcap": "10"
};
$.each(response, function (key, value) {
$('[name="room[' + key + ']"]').val(value);
});
});
Related
I've implemented a dynamic selection, where users will choose the project they are working on in one selection and then a dropdown with several "subtasks" will appear.
This works but only about 50% of the time, sometimes the second dropdown contains all projects with their subtasks, other times the subtasks will populate based on on the project selected.
This is my Task.js function:
function showForm() {
const btn = document.getElementById('new-task-form')
btn.style.display == "block" ? btn.style.display = "none" : btn.style.display = "block"
}
jQuery(function() {
let subtasks;
subtasks = $('#task_subproject_id').html();
return $('#task_project_id').change(function(){
let project, optons;
project = $('#task_project_id :selected').text();
options = $(subtasks).filter("optgroup[label='" + project + "']").html();
if(options) {
return $('#task_subproject_id').html(options);
} else {
return $('#task_subproject_id').empty();
}
});
});
This is the new partial where the collections are displayed:
<%= form_for(#task, method: :post, remote: true, html: {class: "form-group"}) do |f| %>
<%= f.label "Describe the task"%>
<%= f.text_field :comments, id: "task-comments", class: "form-control" %>
<br />
<%= f.label "Time in minutes" %>
<%= f.text_field :time, class: "form-control" %>
<%= f.label "Project" %>
<%= f.collection_select :project_id, Project.order(:name), :id, :name,
{prompt: "Select a project"}, {class: "form-control"} %>
<br />
<%= f.grouped_collection_select(:subproject_id, Project.order(:name), :subprojects, :name,
:id, :name, {prompt: "Select a subtask" },{class: "form-control"}) %>
<br / />
<%= f.label "Date" %>
<%= f.date_select :day, {class: "form-control"}%>
<br />
<%= f.label "Collaborators" %>
<ul class="list-group collaborators">
<%= f.collection_check_boxes(:user_ids, User.where.not(id: current_user.id), :id, :email_or_user_name) do |box| %>
<li class="list-group-item"> <%= box.check_box + box.text%> </li>
<% end %>
</ul>
<%= f.submit "Add Task", class: 'btn btn-primary' %>
<% end %>
Again this works about 50% of the time. I've tried it in multiple browsers; Safari, Chrome, IE, Opera does not seem to be a browser issue, and when it dosen't work there is not console error.
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..
I have created a nested model form for Lessons to Questions and Answers. It was not picking up the coffee script so I have add it the coffee code as Javascript but i am get an error and Add Question is not working. Anyone and assist please.
Lesson.rb
has_many :questions
accepts_nested_attributes_for :questions, :allow_destroy => true
Question.rb
belongs_to :lesson
has_many :answers
accepts_nested_attributes_for :answers, :allow_destroy => true
Answer.rb
belongs_to :question
application_helper.rb
def link_to_add_fields(name, f, association) new_object = f.object.send(association).klass.new
id = new_object.object_id
fields = f.fields_for(association, new_object, :child_index => id) do |builder|
render(association.to_s.singularize + "_fields", :f => builder)
end
link_to(name, '#', :class => "add_fields", :data => {:id => id, :fields => fields.gsub("\n", "")}) end
admin/lessons/_form.html.erb
<%= form_for([:admin,#lesson]) do |f| %>
<% if #lesson.errors.any? %>
<div class="notification error png_bg">
<img src="/assets/admin/icons/cross_grey_small.png" title="Close this notification" alt="close" />
<div>
<h2><%= pluralize(#lesson.errors.count, "error") %></h2>
<ul>
<% #lesson.errors.full_messages.each do |msg| %>
<li><%= msg %></li>
<% end %>
</ul>
</div>
</div>
<% end %>
<label class="formlabel">Lesson Title</label>
<%= f.text_field :title %>
<%= f.fields_for :questions do |builder| %>
<%= render 'question_fields', :f => builder %>
<% end %>
<%= link_to_add_fields "Add Question", f, :questions %>
<%= f.submit 'Save', :class => 'button' %>
_question_fields.html.erb
<fieldset>
<%= f.label :content, "Question" %><br />
<%= f.text_area :content %><br />
<%= f.check_box :_destroy %>
<%= f.label :_destroy, "Remove Question" %>
<%= f.fields_for :answers do |builder| %>
<%= render 'answer_fields', :f => builder %>
<% end %>
<%= link_to_add_fields "Add Answer", f, :answers %>
</fieldset>
_answer_fields.html.erb
<fieldset>
<%= f.label :content, "Answer" %>
<%= f.text_field :content %>
<%= f.check_box :_destroy %>
<%= f.label :_destroy, "Remove Answer" %>
</fieldset>
Here is the javascript I have added just before the end of the the head tag. I am getting an error of "$('form').on is not a function. (In '$('form').on', '$('form'....
<script>
jQuery(function() {
$('form').on('click', '.remove_fields', function(event) {
$(this).prev('input[type=hidden]').val('1');
$(this).closest('fieldset').hide();
return event.preventDefault();
});
return $('form').on('click', '.add_fields', function(event) {
var regexp, time;
time = new Date().getTime();
regexp = new RegExp($(this).data('id'), 'g');
$(this).before($(this).data('fields').replace(regexp, time));
return event.preventDefault();
});
});
</script>
Jquery .on() function needs at least jquery 1.7 to work. Update your jquery or use .bind() in place of .on().
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 used devise to integrate user registration and login. Now I also have forgot password page.
What would be the best way to pass user's email from the user_email textfield on the login form to the forgot password form, so the user doesn't need to put in his/her email twice?
Link to forgot password page:
<%- if devise_mapping.recoverable? && controller_name != 'passwords' && controller_name != 'registrations' %>
<%= link_to "Forgot your password?", new_password_path(resource_name) %><br />
<% end -%>
Sign in form:
<%= form_for(resource, as: resource_name, url: session_path(resource_name)) do |f| %>
<div><%= f.label :email %><br />
<%= f.email_field :email, autofocus: true, :required => true %></div>
<div><%= f.label :password %><br />
<%= f.password_field :password, autocomplete: "off", :required => true %></div>
<% if devise_mapping.rememberable? -%>
<div><%= f.check_box :remember_me %> <%= f.label :remember_me %></div>
<% end -%>
<div><%= f.submit "Sign in" %></div>
<% end %>
Forgot password form:
<%= form_for(resource, as: resource_name, url: password_path(resource_name), html: { method: :post }) do |f| %>
<%= devise_error_messages! %>
<div><%= f.label :email %><br />
<%= f.email_field :email, autofocus: true %></div>
<div><%= f.submit "Send me reset password instructions" %></div>
<% end %>
Just try this
<%= f.email_field :email, autofocus: true, object: resource %></div>