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 + "€");
});
});
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 this makeid function which returns a random string of 10 characters
function makeid() {
var text = "";
var possible = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789";
for (var i = 0; i < 10; i++)
text += possible.charAt(Math.floor(Math.random() * possible.length));
return text;
}
I want to manually put this string to my devise form like this :
<div class="user_field">
<div class="email">`enter code here`
<%= f.label :email %><br />
</div>
<%= f.email_field :email, autofocus: true, autocomplete: "email" , value: <script>makeid();</script>%>
</div>
Any thoughts??
Rewrite your makeid function as a ruby method, and put it into app/helpers/application_helper.rb
def makeid
(('A'..'Z').to_a + ('a'..'z').to_a + (0..9).to_a).sample(10).join()
end
Then you can call that helper in your templates:
<div class="user_field">
<div class="email">`enter code here`
<%= f.label :email %><br />
</div>
<%= f.email_field :email, autofocus: true, autocomplete: "email" , value: makeid() %>
</div>
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
I want to call a JS function when a button in my Rails form is clicked. The function is defined in the .js.erb file found below.
When I click the button, Chrome's JS console throws the following error:
Uncaught ReferenceError: logTime is not defined
I know this means it can't find the function, but I don't see why. Especially since I added <%= javascript_include_tag "track.js.erb" %> to the file. Any ideas?
Apologies up-front, but my Google-fu yielded no results.
_track_time_form.html.erb
<div id="countdown-timer"></div>
<div id="playback-button">►</div>
<div id="track-time-form">
<%= form_for #project, :url => { :action => "log_time" }, remote: true do |p| %>
<ul>
<li><%= p.label :project, "Project:"%><br>
<%= p.collection_select(:id, current_user.projects, :id, :name) %></li>
<%= p.hidden_field :time_logged, :value => 0 %> <!-- value set by script in log_time.js.erb -->
<li><%= p.submit "Log time", id: "log-time-button", :onclick => "logTime()" %></li>
</ul>
<% end %>
</div>
The function the handler is calling can be found here:
track.js.erb
//initialise form
timeTrackingForm = window.open("", "", "height=700,width=500");
$(timeTrackingForm.document.body).html("<%= j render( :partial => 'track_time_form' ) %>");
//assign variables
var timer = $("#countdown-timer", $(timeTrackingForm.document));
var playbackControls = $("#playback-button", $(timeTrackingForm.document));
var form = $("#track-time-form", $(timeTrackingForm.document));
var formUl = $("#track-time-form ul", $(timeTrackingForm.document));
var formLi = $("#track-time-form li", $(timeTrackingForm.document));
var logTimeButton = $("#log-time-button", $(timeTrackingForm.document));
var timerPaused;
//initialise timer
$(timeTrackingForm.document).ready(function(){
initialiseTimer();
style();
$(playbackControls).click(function() {
playOrPause();
});
});
function initialiseTimer() {
$(timer).timer({
format: '%H:%M:%S'
});
$(timer).timer('pause');
timerPaused = true;
}
function style() {
$(timer).css({'color':'black','font-size':'50px', 'margin':'auto', 'width':'180px'});
$(playbackControls).css({'color':'#290052', 'font-size':'50px', 'margin':'auto', 'width':'55px'});
$(form).css({'width':'300px','margin':'auto'});
$(formUl).css({'list-style-type':'none'});
$(formLi).css({'margin':'0 0 25px 0','font-sizeL':'18px','font-family':'Arial'});
$(logTimeButton).css({'width':'180px','font-size':'18px','background-color':'green','color':'white','margin-top':'15px'});
}
function playOrPause() {
if (timerPaused == true) {
$(timer).timer('resume');
timerPaused = false;
}
else {
$(timer).timer('pause')
timerPaused = true;
}
}
function logTime() {
$(timer).timer('pause');
var secondsTracked = $(timer).data('seconds');
$('input:hidden').val(secondsTracked);
$('#countdown-timer').timer('reset');
}
For any future readers interested in the solution, here's how I got around the issue (huge thanks to the helpful commenters above).
I added an event listener to the form in track.js.erb, which is triggered when the button is clicked (but before the form actually submits and sends data to the controller). Here it is:
var actual_form = $("#new_project", $(timeTrackingForm.document));
$(actual_form).submit(function(){
$(timer).timer('pause');
timerPaused = true;
var secondsTracked = $(timer).data('seconds');
$(hidden).val(secondsTracked);
resetTimerDisplay();
});
I have two blocks with checkboxes. I'm trying to check this particular checkboxes with JS.
<%= hidden_field_tag "user[roles][]" %>
<% User.valid_roles.map{|c| {name: c, id: User.mask_for(c)} }.each do |role| %>
<%= check_box_tag "user[roles][]", role[:name], user.has_role?(role[:name]), id: "user_role_#{role[:id]}" %>
<%= label_tag "user_role_#{role[:id]}", role[:name].to_s.titleize %><br/>
<% end %>
$('#selectAll').click(function() {
if(this.checked) {
$(':checkbox').each(function() {
this.checked = true;
});
} else {
$(':checkbox').each(function() {
this.checked = false;
});
}
});
Something like this should work:
$('#selectAll').on('change', function(){
var checkboxes = $('input[id^="employer_"]');
var checkedValue = !!this.checked;
checkboxes.prop('checked', checkedValue);
});
Here is a fiddle to demonstrate: http://jsfiddle.net/f5nx0czv/
With jQuery you can set a property/attribute en masse, no need to iterate over the collection.