jQuery, display result of function on next click - javascript

I trying to make auto price calculation on magento 2.1 product. When i test my code on snippet or jsfiddle it works normally, but when runs on real magento site the result of "mouseup" calculate function will display on next click (or from previous click) but on "keyup" worked fine. Did someone have any answers for this case?
$(document).ready(function(){
$(".control").on("keyup mouseup",function(){
var totale = 0;
$(".quantity-number .qty").each(function () {
var qty = parseFloat($(this).val());
//var price = parseFloat($(".price-wrapper").attr("data-price-amount"));
//var price = parseFloat($(".price").attr("data-price-amount"));
//var price = parseFloat($(".price").text());
var price = parseFloat($('.product-info-main span.price').text().match(/\d+/)[0], 10);
/*
var temp=$(".price").text();
var num = temp.match(/[\d\.]+/g);
if (num != null){
var price = num.toString();
}
*/
totale += qty * price;
totale = qty * price;
});
$(".cal-price").html("฿"+totale.toFixed(2));
});
});
<script src="https://code.jquery.com/jquery-3.1.1.min.js"></script>
<div class="product-info-main">
<span class="price-wrapper" data-price-amount="10">
<span class="price">
฿10.00
</span>
<div class="control">
<div class="quantity-number">
<input type="number" name="qty" id="qty" maxlength="12" value="1" title="Quantity" class="input-text qty">
</div>
<span class="cal-price"></span>
</div>
https://jsfiddle.net/l2esforu/x6332ay3/

If you are wanting to call the function when the value is changed in the input element, add an event listener for the "input" event on the input element itself.
$("#qty").on("input", function () { ... });
However, if you have several quantity inputs, and they are added dynamically, you will want to use a delegate selector like so:
$(".control").on("input", ".qty", function () {
// do stuff
});
Event Delegation Docs

My problem is SOLVED! thanks
After try using every state may happening on main div.
$(document).on("input keyup change click mouseup",".control",function(){
$(".quantity-number .qty").each(function () {
//do stuff
});
}

Related

Dropdown with numbers from 1 - 10 and total price below must change

I am trying to create a drop down with numbers from 1 - 10 for example. Once a number is selected, it should change the total amount. However I have not succeeded and not sure what else I should do, please help.
I have got something put together so far.
<div class="checkout">
<input type="number" name="quantity" placeholder="How many would you like to order? (numeric numbers only)" class="quantity price" data-price="49" value="">
<p class="total" style='margin-bottom: 0px;' >Total: <span id="total">R49 per month</span></p>
</div>
<script type='text/javascript'>
$(document).ready(function(){
$(".checkout").on("keyup", ".quantity", function(){
var price = +$(".price").data("price");
var quantity = +$(this).val();
$("#total").text("R" + price * quantity);
})
})
var foo = document.getElementById('.checkout');
foo.addEventListener('focus', function () {
foo.setAttribute('data-value', this.value);
this.value = '';
});
foo.addEventListener('blur', function () {
if (this.value === '')
this.value = this.getAttribute('data-value');
});
</script>
All I need is to change the type from a number to a drop down.

Using If/else statement to value according to slider value

I am trying to change how value displayed using slider. I have made a label that display the value as below.
Course Duration : 1 day
the value displayed in here is changing according to the slider value.
so, when the slider value is in 1, it should be displayed as "day" and when the slider value greater than 1, it should be displayed as "days".
I have used if/else statement within my javascript to change the name displayed according to the slider value. The coding I used as below.
JS file :
// method used to get value from slider and display.
function slider_value() {
var slider = document.getElementById("myRange");
var output = document.getElementById("demo");
output.innerHTML = slider.value;
slider.oninput = function () {
output.innerHTML = this.value;
}
}
// method used to change name according to slider value
function value_name() {
var count = document.getElementById("myRange");
var outname = document.getElementById("dname");
if (parseInt(count.value) == 1) {
outname.innerHTML = "Day";
}
else {
outname.innerHTML = "Days";
}
}
HTML file:
<label for="duration">
Course Duration :
<span id="demo"></span>
<span id="dname"></span>
</label>
<div class="slidecontainer">
<input type="range" min="1" max="15" value="1" class="slider" id="myRange">
</div>
I have called the functions to the view as below:
<script>
slider_value();
value_name();
</script>
Coding won't show any errors while debugging but it only shows day or days and won't change according to the slider value. so I am expecting some help and ideas to rectify this.
Thanks a bunch.
You need to use the oninput and onchange events of the input element, such as:
oninput="slider_value(this.value)" onchange="slider_value(this.value)" .
Use both for full compatibility, since oninput is not supported in IE10.
Small example here, to get you started:
https://codepen.io/anon/pen/ewBNGj
Notice that the function that sets the day/days string ( value_name() ) is called from within the slider_value() function.
No need for complex js calculations, you could easily do this with the change event. add event listener to the input and then add you logic there, checkout the snippet
var el = document.getElementById('myRange');
el.addEventListener('change', function(event){
var value = event.target.value;
var _container = document.getElementById('demo');
value == 1 ? _container.innerText = value+' Day' : _container.innerText = value+' Days'
})
<label for="duration">
Course Duration :
<span id="demo"></span>
<span id="dname"></span>
</label>
<div class="slidecontainer">
<input type="range" min="1" max="15" value="1" class="slider" id="myRange">
</div>
Wrap the formatting of the slider's text in a function
function updateSlider(e) {
if (parseInt(e.value) == 1) {
output.innerHTML = parseInt(e.value) + " Day";
} else {
output.innerHTML = parseInt(e.value) + " Days";
}
}
This way you can call it once initially and populate the text properly. To update the contents of the slider as something changes add the input event listener and call this function from there.
Here's an example:
var slider = document.getElementById("myRange");
var output = document.getElementById("demo");
slider.oninput = function(e) {
updateSlider(e.target);
}
function updateSlider(e) {
if (parseInt(e.value) == 1) {
output.innerHTML = parseInt(e.value) + " Day";
} else {
output.innerHTML = parseInt(e.value) + " Days";
}
}
updateSlider(slider);
<label for="duration">
Course Duration :
<span id="demo"></span>
<span id="dname"></span>
</label>
<div class="slidecontainer">
<input type="range" min="1" max="15" value="1" class="slider" id="myRange">
</div>

How to add and substarct value in javascript on keyup event?

I am trying to do one task using javascript, i have two text boxes one is for total amount and second is for discount and i have value in total amount for example 100 and when i insert discount in discount text box that inserted discount must be subtract from total amount but when i remove that discount that value must be as previous i tried below but it substract value but when it removes discount it does not work please help. Thanks in advance.
$(".form-basic .grand-discount").on('keyup', function () {
var gross= $('input[name="total_gross_amount"]').val();
var totalDiscount = $(this).val();
if(totalDiscount != '')
{
var total=gross-totalDiscount;
}
else{
var total=gross+totalDiscount;
}
$('input[name="total_gross_amount"]').val(total);
});
$(".form-basic .grand-discount").on('keyup', function () {
var gross= $('input[name="total_gross_amount"]').val();
var totalDiscount = $(this).val();
if(totalDiscount.length>0) {
var total=gross-totalDiscount;
} else{
var total=gross;
}
$('input[name="total_gross_amount"]').val(total);
});
Try this one.
As #Chris G proposed in comments and I edited his fiddle(just an example how this could be done, but since the questioner did not provide all info, this is what we have done):
$(".form-basic input").on('input', function() {
var gross = $('input[name="total_gross_amount"]').val();
var totalDiscount = $('.grand-discount').val();
var total = gross - totalDiscount;
$('#total').html(total);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form class="form-basic">
<input type="number" class="total_gross_amount" name="total_gross_amount">
<input type="number" class="grand-discount" name="grand-discount">
</form>
<p>Total: <span id="total"></span></p>
I think this solve your problem, the key is to take gross out of input event:
$(document).ready(function(){
var gross= $('input[name="total_gross_amount"]').val();
$(".form-basic .grand-discount").on('keyup', function () {
var totalDiscount = $(this).val();
if(totalDiscount != '')
{
var total=gross-totalDiscount;
}
else{
var total=gross+totalDiscount;
}
$('input[name="total_gross_amount"]').val(total);
});
});
ful example here https://jsfiddle.net/wkj0jjvp/
if you want to update gross amount, you should set an event for gross and put inside the discount event.

Jquery input radio field add percentage

I need to be able to add a percentage to the total price when a radio button is selected. The code currently works, but only adds a value to the radio button. I need that, but also need to take the total calculated price with addOns and + a percentage to it.
Does anyone know how I can change this with Jquery?
Thanks in advance.
Jsfiddle: http://jsfiddle.net/4bitlabs/mGLfk/5/
HTML:
<div class="price">Estimate Price $<label for="amount1" class="total">0</label></div>
<p class="itemdesc1">How many "Linear Feet" of boards do you have?</p>
<input id="amount1" class="amount" data-for="amount1" />
<div class="addon"><input id="amount2" type="checkbox" value="10.00" class="radio addOn" data-for="amount1" />Add Red $10.00</div>
<div class="addon"><input id="amount3" type="checkbox" value="20.00" class="radio addOn" data-for="amount1" />Add Blue + 20%</div>
Jquery:
$(function () {
$('.amount').keypress(function () {
changeAmount($(this));
});
$('.addOn').change(function () {
var $original = $('#' + $(this).data('for'));
changeAmount($original);
});
});
function changeAmount($element) {
var amount = 0;
amount = parseFloat($element.val()) * 20;
if (isNaN(amount)) {
amount = 0;
}
var id = $element.attr('id');
$('.radio:checked[data-for="' + id + '"]').each(function () {
amount += parseFloat($(this).val());
});
$('label[for=' + id + ']').text(amount.toFixed(0))
}
Ok, I would rewrite what I understand from your question, please, correct me if I'm wrong...
You have CHECKBOXES, and you have an input where you may write a number of items you want to purchase. Then, you want to know the final price of the items you purchase, applying some considerations depending on what CHECKBOX are clicked.
Well, that said, I'll start first assuring you always trigger an "adding function" when anything changes (let's say, you change the number of inputs, or you click a checkbox). You almost did it, but you pass a parameter and I think that is not necessary. When you'll trigger anytime the calculation, you'll always have the right result.
Other thing, you need to distinguish between "adding checkbox" (adds a price per item) and "percentage checkbox" (adds a percentage to the price), to know what value you have to add. Just add clases to your checkboxes to distinguish between them. I'll add a fiddle:
Changes:
The clasess in the checkboxes, to know what we want to do with any of them, put attention on the add and percentage clasess:
<div class="addon"><input id="amount2" type="checkbox" value="10.00" class="radio addOn add" data-for="amount1" />Add Red $10.00</div>
<div class="addon"><input id="amount3" type="checkbox" value="20.00" class="radio addOn percentage" data-for="amount1" />Add Blue + 20%</div>
Your function adding must be called anytime you change anything, to allow you know what is changed, and set price to zero when changing the value (optional).
$('.amount').keydown(function () {
$('.price label').text('0');
});
$('.amount').keyup(function () {
changeAmount();
});
$('input:checkbox').change(function () {
changeAmount();
});
And last, depending on the class of checkbox clicked, different calculation:
function changeAmount() {
var $amount = 0;
$amount = parseFloat( $('.amount').val() ) * 20;
if (isNaN($amount)) {
$amount = 0;
}
var $add = 0;
$('.add:checked').each(function () {
$add += parseFloat( $(this).val() );
});
// Calculate percentage of the Base product
if ( $('.percentage').is(":checked") ) {
$amount = $amount * (1 + $('.percentage').val()/100 );
}
var $total = parseFloat( $amount + $add );
$('.price label').text( $total.toFixed(0) )
}
The fiddle: http://jsfiddle.net/mGLfk/11/
Hope it likes you! XD
I think I got it http://jsfiddle.net/mGLfk/10/
First, use keyup instead of keypress. I added two separate class for percent and sum.
function changeAmount($element) {
var amount = 0;
amount = parseFloat($element.val()) * 20;
if (isNaN(amount)) {
amount = 0;
}
var id = $element.attr('id');
$('.sum.radio:checked[data-for="' + id + '"]').each(function () {
amount += parseFloat($(this).val());
});
var percentage=100;
$('.percent.radio:checked[data-for="' + id + '"]').each(function () {
percentage += parseFloat($(this).val());
});
amount*=(percentage/100);
$('label[for=' + id + ']').text(amount.toFixed(0))
}

Javascript increment a value

I have tried and failed trying to get this to work so time to ask the experts.
I've got the following HTML:
<input type="button" value="-" class="minus">
<input type="number" value="20" class="input-text">
<input type="button" value="+" class="plus">
<div class="newprice">
20
</div>
Using javascript (jQuery specific is fine) I need to be able to have it so that when someone clicks the plus button, the number inside the .newprice div gets incremented by 20. Likewise when they hit the minus button the number gets decreased by 20.
Also the same goes for if they use the little up/down arrows on the .input-text field.
Or if they type in a value instead of using any of the buttons, then the number in the .input-text div changes accordingly (if someone typed in 3, the .input-text number would change to 60).
PS: if it's easier the .newprice div can be an text field instead. Whatever works.
[To put this all into context, basically its part of a shopping cart but I am trying to show the user how much they will be paying for the product when they enter a quantity. For example, the product costs $20, and if they want 3 of them they will be able to see straight away (before adding to their cart) that this is going to cost them $60.]
I hope I explained it properly.
Thanks in advance.
You can do this.
// how many to increment each button click
var increment = 20;
$('.plus, .minus').on('click', function() {
// the current total
var total = parseInt($('#newprice').text());
// increment the total based on the class
total += (this.className == 'plus' ? 1 : -1) * increment;
// update the div's total
$('#newprice').text(total);
// update the input's total
$('.input-text').val(total);
});
$('.input-text').on('change', function() {
// update the div's total
$('#newprice').text( $(this).val() );
});
Edit based on comments
// how many to increment each button click
var increment = 20;
$('.plus, .minus').on('click', function() {
// the current total
var total = parseInt($('#newprice').text());
// increment the total based on the class
total += (this.className == 'plus' ? 1 : -1) * increment;
// update the div's total
$('#newprice').text(total);
});
$('.input-text').on('change', function() {
// update the div's total
$('#newprice').text( $(this).val() );
});
To increment the number input by 20, add the attribute step like so. The number in that attribute represents how much the value will be incremented each time the up and down buttons are pressed.
<input type="number" value="20" step="20" class="input-text">
I already add some calculation and html for handle the basic price. See demo in jsfiddle
HTML:
Price per item:<input name="basicPrice" value="20" class="input-text">
<br />
<input type="button" value="-" class="minus">
<input name="quantity" id="quantity" type="number" value="1" class="input-text">
<input type="button" value="+" class="plus">
<br />Money much pay:
<span class="newprice">20</span>
JS by jquery :
function calculate(){
var basicPrice = parseInt($(":input[name='basicPrice']").val());
var quantity = parseInt($(":input[name='quantity']").val());
console.log(quantity);
var total = basicPrice * quantity;
$(".newprice").text(total);
}
function changeQuantity(num){
$(":input[name='quantity']").val( parseInt($(":input[name='quantity']").val())+num);
}
$().ready(function(){
calculate();
$(".minus").click(function(){
changeQuantity(-1);
calculate();
});
$(".plus").click(function(){
changeQuantity(1);
calculate();
});
$(":input[name='quantity']").keyup(function(e){
if (e.keyCode == 38) changeQuantity(1);
if (e.keyCode == 40) changeQuantity(-1);
calculate();
});
$(":input[name='basicPrice']").keyup(function(e){
calculate();
});
var quantity = document.getElementById("quantity");
quantity.addEventListener("input", function(e) {
calculate();
});
});
Let's me know if you need any support.
You can do...
var $counter = $('.counter');
$('button').on('click', function(){
var $button = $(this);
$counter.text(function(i,val){
return +val + ( $button.hasClass('up') ? 1 : - 1 );
});
});
with this HTML...
<div class="counter">10</div>
<button class="down">-</button>
<button class="up">+</button>
For the record, you should definitely be using an input for the counter element.
Here's your pure JS example but I believe to catch anything below IE9 you'll have to attach event listeners as well.
jsFiddle
<form>
<input type="button" id="value-change-dec" value="-">
<input type="text" id="new-price" value="0" disabled>
<input type="button" id="value-change-inc" value="+">
<br>
<input type="number" id="change-price">
</form>
document.getElementById("value-change-dec").addEventListener("click", function() {
var value = parseInt(document.getElementById('new-price').value);
value=value-20;
document.getElementById('new-price').value = value;
});
document.getElementById("value-change-inc").addEventListener("click", function() {
var value = parseInt(document.getElementById('new-price').value);
value=value+20;
document.getElementById('new-price').value = value;
});
function changeIt() {
document.getElementById('new-price').value = document.getElementById('change-price').value*20;
}
var changer = document.getElementById('change-price');
changer.addEventListener('keydown', changeIt, false);
changer.addEventListener('keyup', changeIt, false);
changer.addEventListener('click', changeIt, false);

Categories