Jquery input radio field add percentage - javascript

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))
}

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.

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, display result of function on next click

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
});
}

Adding to variable value on condition in Javascript

I have a variable called "total" that I would like to assign a number (or price) to and then add to that number when certain options are selected or checked. Here is the code I have so far.
Here is the code that sets the initial value (base price) of the variable that will be added to. THIS CODE CURRENTLY WORKS.
$('input[name=trimlevel]').change(function(){
var total = 0;
if(document.getElementById('basetrim').checked==true) {
var total = 0;
var basetrim = 3550.00;
total = total + basetrim;
$('#myTotal').html('$' + total);
}else if(document.getElementById('upgrade').checked==true) {
var total = 0;
var upgrade = 2400.00;
total = total + upgrade;
$('#myTotal').html('$' + total);
}else {
$('#myTotal').html('$' + total);
}
});
Here is an example of the code used to "add to" the value of the variable. THIS IS NOT WORKING.
$('input[name=leather]').change(function(){
if(document.getElementById('leather).checked == true) {
var leather = 180.00;
total = total + leather;
$('#myTotal').html('$' + total);
}
});
Here is the HTML for reference
<div class="modelsel">
<h2>1. SELECT MODEL</h2> <br>
<label for="basetrim">BASE MODEL</label>
<input id="basetrim" type="radio" name="trimlevel" value="2400.00">
<label for="upgrade">UPGRADED MODEL</label>
<input id="upgrade" type="radio" name="trimlevel" value="3550.00">
</div>
<div class="inside">
<h2>3. BASE MODEL ADD-ONS</h2><br>
<input type="checkbox" value="180.00" id="leather" name="leather" />
<label for="leather">Leather Seat (+ $180.00)</label><br>
</div>
<div id="myTotal"></div>
I am relatively new to Javascript and have been struggling with this for hours. Any help is appreciated. Thanks in advance.
Only some modifications need to be made in order to get things to work:
First one, there's a typo here:
if(document.getElementById('leather).checked == true) {
You missed a ' so substitute it by:
if(document.getElementById('leather').checked == true) {
Second, define the var total out of the functions and make it available to all of them. If you have your methods in the ready function you can define total there. Also remove the definition of total inside the functions or you won't use the one who is defined in ready.
Third, when the user clicks the checkbox, you're always adding value (don't know if that's what you want). In this fiddle, I add or diminish the amount of total according to the state of the checkbox.
The solution is already in the comments. The context of the functions is different. You can either define total outside of the functions or use an object for your behavior.
var someObject = {};
inside your function you can write with the dot notation.
someObject.total = 10;
$('input[name=trimlevel]').change(function(){
var total = 0;
if($(this).checked==true)) {
total = total + $(this).val();
}
$('#myTotal').html('$' + total);
});
Consider writing a comprehensive named function which adds up everything that can possibly contribute to your total :
function calculate() {
var total = 0;
if(document.getElementById('basetrim').checked) {
total = total + 3550.00;
} else if(document.getElementById('upgrade').checked) {
total = total + 2400.00;
}
if(document.getElementById('leather').checked) {
total = total + 180.00;
}
// further additions here
// further additions here
// further additions here
$('#myTotal').html('$' + total);
});
Then attach that named function as the event handler wherever necessary :
$('input[name=trimlevel]').change(calculate);
$('input[name=leather]').change(calculate);
//further attachments of calculate as event handler here
//further attachments of calculate as event handler here
//further attachments of calculate as event handler here

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