I have 3 models Dealer, Label, Number
The relations between models
dealer and label - habtm,
dealr and number - has_many through labels,
label and number - has many.
my first drop down to select dealers, based on that 2nd drop down has to display the labels
f.input :dealer, :input_html => {
:onchange => "
var dealer = $(this).val();
$('#contact_number_id').val(0).find('option').each(function(){
var $option = $(this),
isCorrectDealer = ($option.attr('data-dealer') === dealer);
$option.prop('hidden',!isCorrectDealer);
});
"
}
f.input :label, collection: Label.all.map{
|v| [v.label_name,v.id, {"data-dealer" => v.dealer_id}]
}
It is not working for me...Please help me with this
Related
Hi I am trying to mulitiplay two text_field(input) value and display it in another text_field(input) in Rails
for example like in jquery we do like this please test it http://jsfiddle.net/qw5xM/
I want this thing in rails how to do that, what i am missing here
my form is bellow
<%= form_for #fills, url: { action: "show"}, method: :get do |f| %>
//updated code
<div class="row text-center row-create" style="margin-left: 0%">
<div class="pull-right col-create" style="margin-right: 0%; border-radius: 50%;">
<div class="col-xs-1 col-sm-1">
<%= f.button "+" , class: 'btn btn-default bg-red', style: 'border-radius:50%' %>
</div>
</div>
// till here
<div class="col-xs-2 col-sm-2">
<div class="form-group has-feedback">
<%= f.hidden_field :price, value: #price_log.price %>
<%= f.text_field :quantity, value: 1, required: true, class:'form-control', id: 'quantiy', placeholder: 'Quantity' %>
</div>
</div>
<div class="col-xs-2 col-sm-2">
<div class="form-group has-feedback">
<%= f.text_field :amount, value: :total_price , class:'form-control', placeholder: 'Amount', id: 'total_price' %>
</div>
</div>
<% end %>
and my jquery code is
$('text_field[name="quantity"]').keyup(function() {
var a = $('hidden_field[name="price"]').val();
var b = $(this).val();
$('text_field[name="total_price"]').val(a * b);
});
Updated Question
creating the new fields by clicking plus button
<script type="text/javascript">
$(document).on('click','.col-create',function(e){
e.preventDefault();
var cont = $(this).closest('.row-create').clone();
$(cont).find(".col-create").remove().end().insertAfter($(this).closest('.row-create'));
e.preventDefault()*;
});
On click plus button it should be create new field same as above and the multiplying script should work separately for each new fields.
I want to create new one and save all new created values also.
But this one saving only first value.
please any help must appriceated
Thanks a lot
you can also write
$('input[name="textbox2"]').keyup(function() {
var first = $('input[name="textbox1"]').val();
var second = $(this).val();
$('input[name="textbox3"]').val(first * second);
});
Its always good practice to select an attribute with id or class instead of name attribute,
provide a id to hidden field price to get its value easily, rest all are good so far and try this: -
<%= f.hidden_field :price, value: #price_log.price, id: "price" %>
$('#quantiy').on('keyup', function(e) {
var price = parseFloat($('#price').val());
var quantity = $(this).val();
$('#total_price').val((price * quantity).toFixed(2));
});
You need to change your text_field into input because you cannot use attribute selector with class or id. With attribute selector you can do with following code.
$('input[name="quantity"]').keyup(function() {
var a = $('input[name="price"]').val();
var b = $(this).val();
$('input[name="total_price"]').val(a * b);
});
And with selector you need . for class and # for id. Here is the working code.
$("#quantity").keyup(function() {
var a = $("#price").val();
var b = $(this).val();
$("#total_price").val(a * b);
});
You should use parseInt or parseFloat like this:
$('.text_field[name="quantity"]').keyup(function() {
var a = $('hidden_field[name="price"]').val();
var b = $(this).val();
$('.text_field[name="total_price"]').val(parseFloat(a) * parseFloat(b));
});
Change the below code
$('text_field[name="quantity"]').keyup(function() {
var a = $('hidden_field[name="price"]').val();
var b = $(this).val();
$('text_field[name="total_price"]').val(a * b);
});
to
$('input[name="quantity"]').keyup(function() {
var a = $('input[name="price"]').val();
var b = $('input[name="quantity"]').val();
$('text_field[name="total_price"]').val(a * b);
});
Before writing code, inspect in your browser.
Also, there is something to consider in your logic.
If you enter '3' in first textbox and then enter '4' in second textbox, then the third box will get '12' as value.
But if you again, go to first textbox and change it to '5', it will not print '15'.
So you can change the code as below
$('input[name="quantity"]').keyup(function() {
var a = $('input[name="price"]').val();
var b = $('input[name="quantity"]').val();
$('text_field[name="total_price"]').val(a * b);
});
function multiply() {
var a = $('input[name="price"]').val();
var b = $(this).val();
$('text_field[name="total_price"]').val(a * b);
});
$('input[name="quantity"]').keyup(multiply);
$('input[name="price"]').keyup(multiply);
I have various inputs, each with a different price via data-attribute:
<%= f.number_field :item, class: "test", :data => {:price => '10.25'}
User can select the number of items they want, so I need to multiply the number of items selected by the price of the item.
$( document ).ready(function() {
$(".test").on('change', function() {
a = $(".test").val() * $(".test").data("price") + "€";
$(".resultado").html(a);
});
});
This works great for 1 input, but since I have 4 inputs, each with a different price, I need to get the TOTAL price for the 9 of them.
<%= f.number_field :item, class: "test", :data => {:price => '10.25'} %>
<%= f.number_field :seconditem, class: "test", :data => {:price => '10'} %>
<%= f.number_field :thirditem, class: "test", :data => {:price => '10.75'} %>
<%= f.number_field :fourthitem, class: "test", :data => {:price => '10.50'} %>
Basically, I need to get this:
A: Number of items * price of each item
Sum all of the "A" values
How can I modify my script / classes in order to achieve this?
Thanks a lot.
You can use .each() to multiply value returned .data()
$("input[type=button]").on("click", function() {
let n = 1;
$(".test").each(function() {
n *= $(this).data().price;
});
$(".resultado").html(n);
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js">
</script>
<input type="button" value="click" />
<div class="test" data-price="1"></div>
<div class="test" data-price="2"></div>
<div class="test" data-price="3"></div>
<div class="test" data-price="4"></div>
<div class="resultado"></div>
Assuming each item has a different price and quantity, the following refactoring should work. Here's a JSFiddle with the working demo.
$( document ).ready(function() {
$(".test").on('change', function() {
var total = 0;
$.each( $('.test'), function( key, value ) {
total += $(this).val() * $(this).data("price");
});
$(". resultado").html(total + "€");
});
});
I have Entry model with attribute calories and date. I also have User model with attribute expected_calories. When I display list of the entries it should be red if sum of calories per day is more than expected_calories, otherwise should be green.
entries_controller.rb
def index
#entries = Entry.where(user_id: current_user.id)
#user = current_user
if #user.role == 'admin'
#entries = Entry.all
end
end
index.html.slim
h1 Listing entries
table.table
thead
tr
th Date
th Time
th Content
th Cal
th User
th
th
th
tbody
- if can? :manage, Entry
- #entries.each do |entry|
tr
td = entry.date
td = entry.time.strftime("%H:%M")
td = entry.content
td = entry.cal
td = entry.user.role
td = link_to 'Show', entry
td = link_to 'Edit', edit_entry_path(entry)
td = link_to 'Destroy', entry, data: { confirm: 'Are you sure?' }, method: :delete
br
= link_to 'New Entry', new_entry_path
This is a very quick dirty way of doing this:
- if can? :manage, Entry
- #entries.each do |entry|
tr(style="background-color: #{entry.calories > current_user.expect_calories ? 'red' : 'green'})
I'd recommend you create some css classes. For example:
.expected-calories {
background: green
}
.unexpected-calories {
background: green
}
Then create a method in the helpers/entries_helper:
def expected_calories_class(user, entry)
if user.expected_calories <= entry.calories
'expected-calories'
else
'unexpected-calories'
end
end
So your view would be more readable (and the logic would be testable):
- if can? :manage, Entry
- #entries.each do |entry|
tr(class=expected_calories_class(current_user, entry))
I am using Kaminari for paging in my rails application. I need to select all for items on the current page or every page. The current page is rather simple bundle how can I select all the items on other pages.
file_items_controller.rb
def index
account = Account.includes(:credentials).find params[:account_id]
#page = page_param.to_i
#tab = 'Files'
#sort_by = sort_by
#credential = if params[:credential_id].blank?
account.credentials.first || nil
else
account.credentials.find(params[:credential_id])
end
return unless #credential
file_items = FileItem.file_item_list(#credential.root_folder, sort_by)
#total_count = file_items.count
#max_per_page = file_items.count <= 15 ? 'all' : max_per_page.to_i
file_items_scope = Kaminari.paginate_array(file_items.select(&:file?), total_count: file_items.count).page(page_param)
#file_items = if max_per_page == 'all'
file_items_scope.per(file_items.count) || []
else
file_items_scope.per(max_per_page) || []
end
end
file_items.js
$('a.select-all-current').click(function(e){
e.preventDefault();
$('input:not(:checked)').each(function(_, element){
$(element).click();
});
});
$('a.select-all-files').click(function(e){
e.preventDefault();
$('a.select-all-current').click();
});
index.html.slim
...
.row
ul.file-list
- #file_items.each do |file_item|
li.row.file-item
.col-lg-9
p.label
= "#{file_item[:path]}/#{file_item[:name]}"
p.file-size
= "#{number_to_human_size(file_item[:size]).downcase} | "
.col-lg-1.pull-right
= check_box_tag "file_id_#{file_item[:id]}", file_item[:id], false, class: 'file-box'
...
This example assumes ActiveRecord but you should be able to adapt it to your situation:
class ItemsController < ApplicationController
def index
#items = if params[:per_page] == 'all'
Item.all
else
Item.page( params[:page] ).per( params[:per_page] )
end
end
end
I am trying to get dynamic select menu's working in my Rails application.
I have a model called kase, a model called person and a model called company.
When a user creates a new kase, they are presented with a select field to choose a Person and a select field to choose a Company.
I am trying to make it dynamic, so if they choose company a in the first select field then only employees of company a will be listed in the Person field.
The model associations are as follows:
class Kase < ActiveRecord::Base
belongs_to :company # foreign key: company_id
belongs_to :person # foreign key in join table
belongs_to :surveyor,
:class_name => "Company",
:foreign_key => "appointedsurveyor_id"
belongs_to :surveyorperson,
:class_name => "Person",
:foreign_key => "surveyorperson_id"
-------------------------------------------------
class Company < ActiveRecord::Base
has_many :kases
has_many :people
def to_s; companyname; end
-------------------------------------------------
class Person < ActiveRecord::Base
has_many :kases # foreign key in join table
belongs_to :company
UPDATED JAVASCRIPT
var people = new Array();
<% for person in #people -%>
people.push(new Array(<%= person.company_id %>, '<%=h person.personname %>', <%= person.id %>));
<% end -%>
function personSelected() {
alert('hello world');
appointedsurveyor_id = $('kase_appointedsurveyor_id').getValue();
options = $('kase_surveyorperson_id').options;
options.length = 1;
people.each(function(person) {
if (person[0] == appointedsurveyor_id) {
options[options.length] = new Option(person[0], person[1]);
alert('hello world')
}
});
if (options.length == 1) {
$('kase_surveyorperson_id').hide();
} else {
$('kase_surveyorperson_id').show();
}
}
document.observe('dom:loaded', function() {
$('kase_appointedsurveyor_id').observe('change', personSelected);
});
var people = new Array();
<% for person in #people -%>
people.push(new Array(<%= person.id %>, '<%=h person.login %>'));
<% end -%>
function personSelected() {
alert('hello world');
appointedsurveyor_id = $('company_appointedsurveyor_id').getValue();
options = $('person_appointedsurveyorperson_id').options;
options.length = 1;
people.each(function(person) {
if (person[0] == appointedsurveyor_id) {
options[options.length] = new Option(person[0], person[1]);
}
});
if (options.length == 1) {
$('person_field').hide();
} else {
$('person_field').show();
}
}
document.observe('dom:loaded', function() {
//companySelected(); << remove this
$('person_field').observe('change', personSelected);
});
Try observe_field. http://api.rubyonrails.org/classes/ActionView/Helpers/PrototypeHelper.html#M002183