Textbox value not being multiplied when checkbox selected (HTML & Javascript/JQuery) - javascript

My code updates the CPC textbox when options are selected, but when an agency discount is selected (i.e. the 10% checkbox), it successfully lowers the CPC textbox value by 10% but does not do the same for the Total Cost textbox.
The Total Cost textbox value should be the (CPC textbox value * number of clicks textbox) * percentdiscount multiplier
Can anyone see where I'm going wrong? I'll be happy to clarify further if I haven't explained this very well!
HTML:
<div class="runningtotal">
Running CPC Total (in £): <input id="sum" type="text" readonly="true" value="0.00" data-total="0" />
Total Cost (in £): <input id="totalcost" type="text" readonly="true" value="0 (until clicks specified)" data-total="0" />
</div>
<div class="black_whitelisting">
<h1>4. Blacklist/Whitelist?</h1>
<input type="checkbox" class="blacklist" name="blacklist" value="0.20" id="blacklist_checkbox" onclick="BlacklistFunction()">Blacklist required<br>
<input type="checkbox" class="whitelist" name="whitelist" value="0.30" id="whitelist_checkbox">Whitelist required<br>
</div>
<div class="selecttier">
<h1>5. Number of Clicks</h1>
<input id="numberofclickstextbox" type="text" value="0.00" data-total="0" oninput="calculatetier()" />
</div>
<div class="agencydiscount">
<h1>6. Agency Discount</h1>
<label>
<input type="radio" name="percentdiscount" value="1" checked>
None
</label>
<label>
<input type="radio" name="percentdiscount" id="10percent" value="0.9" onclick="calculatetotalcost10()" >
10% Discount
</label>
<label>
<input type="radio" name="percentdiscount" id="15percent" value="0.85" onclick="calculatetier15()" >
15% Discount
</label>
</div>
Javascript:
jQuery(function($) {
$('input[name="percentdiscount"]').on('change', function() {
applyDiscount();
});
$('input[type=checkbox]').click(function() {
let sum = 0;
$('input[type=checkbox]:checked').each(function() {
sum += parseFloat($(this).val());
});
$('#sum').val(sum.toFixed(2)).data('total', sum);
applyDiscount();
});
function applyDiscount() {
var pc = parseFloat($('input[name="percentdiscount"]:checked').val());
$('#sum').val(function() {
return ($(this).data('total') * pc).toFixed(2);
});
}
});
//to work out total cost
function calculatetier() {
var myBox5 = document.getElementById('numberofclickstextbox').value;
var myBox6 = document.getElementById('sum').value;
var result = document.getElementById('totalcost');
var myResult = myBox5 * myBox6;
result.value = myResult.toFixed(2);
}

Looks like you are calculatetier function isn't being called during the change of discount.
Working Demo: https://codepen.io/punith/pen/gOpaVxr?editors=1010
HTML code
<div class="runningtotal">
Running CPC Total (in £): <input id="sum" type="text" readonly="true" value="0.00" data-total="0" />
Total Cost (in £): <input id="totalcost" type="text" readonly="true" value="0 (until clicks specified)" data-total="0" />
</div>
<div class="black_whitelisting">
<h1>4. Blacklist/Whitelist?</h1>
<input type="checkbox" class="blacklist" name="blacklist" value="0.20" id="blacklist_checkbox" >Blacklist required<br>
<input type="checkbox" class="whitelist" name="whitelist" value="0.30" id="whitelist_checkbox">Whitelist required<br>
</div>
<div class="selecttier">
<h1>5. Number of Clicks</h1>
<input id="numberofclickstextbox" type="text" value="0.00" data-total="0" oninput="calculatetier()" />
</div>
<div class="agencydiscount">
<h1>6. Agency Discount</h1>
<label>
<input type="radio" name="percentdiscount" value="1" checked>
None
</label>
<label>
<input type="radio" name="percentdiscount" id="10percent" value="0.9" >
10% Discount
</label>
<label>
<input type="radio" name="percentdiscount" id="15percent" value="0.85" >
15% Discount
</label>
</div>
JS Code
function calculatetier() {
var myBox5 = document.getElementById('numberofclickstextbox').value;
var myBox6 = document.getElementById('sum').value;
var result = document.getElementById('totalcost');
if(myBox6=="0.00"){
myBox6 =1;
}
console.log(myBox6)
var myResult = myBox5 * myBox6;
result.value = myResult.toFixed(2);
}
jQuery(function($) {
$('input[name="percentdiscount"]').on('change', function() {
applyDiscount();
});
$('input[type=checkbox]').click(function() {
let sum = 0;
$('input[type=checkbox]:checked').each(function() {
sum += parseFloat($(this).val());
});
$('#sum').val(sum.toFixed(2)).data('total', sum);
applyDiscount();
});
//to work out total cost
function applyDiscount() {
var pc = parseFloat($('input[name="percentdiscount"]:checked').val());
$('#sum').val(function() {
return ($(this).data('total') * pc).toFixed(2);
});
calculatetier()
}
});

try to use onchange event instead I guess the event you are binding is not correct
<input id="numberofclickstextbox" type="text" value="0.00" data-total="0" onchange="calculatetier()" />

Related

How to subtract two div by their ID?

I have some range sliders and input fields. From that I'm getting some equations now I want to subtract those dynamic numbers by their ID. Below is the code but I'm getting NaN value. Below the steps, I've done.
Getting #totalavgtime from the multiplication of range slider and .averagetime
Getting #timetoproduce from the multiplication of range slider and .radio-roi next input value.
Now trying to subtract #totalavgtime - #timetoproduce but getting NaN value in #timesaving.
$(document).ready(function() {
$(".range").on("change", function() {
var mult = 0;
$('.range').each(function(i) {
var selector_next = parseInt($(".averagetime:eq(" + i + ")").attr("value"))
mult += parseInt($(this).val()) * selector_next //multply..
console.log($(".averagetime:eq(" + i + ")").attr("value"), $(this).val())
})
$("#totalavgtime").val(mult)
})
});
$(document).ready(function() {
$('.range').on('change', function() {
let n = $(this).attr('id').match(/\d+/g)[0];
let total = 0;
let checkVal = $('.radio-roi:checked').next('input').val();
let multiplyFactor = parseFloat(checkVal);
console.log(multiplyFactor)
$('.range').each(function() {
total += (parseFloat($(this).val()) * multiplyFactor);
});
$('#timetoproduce').value(total);
})
});
$(document).ready(function() {
var txt1 = parseInt(document.getElementById("totalavgtime").value);
var txt2 = parseFloat(document.getElementById("timetoproduce").value);
var res = document.getElementById("timesaving");
Number(txt1);
Number(txt2);
//Substract that
res.value = txt1 - txt2;
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<input type="radio" id="" class="radio-roi" name="plan" value="plus" checked>
<input type="text" value="2.5" id="actualtime2" class="hiden-actual-time" disabled><br>
<input type="radio" id="" class="radio-roi" name="plan" value="pro">
<input type="text" value="3" id="actualtime3" class="hiden-actual-time" disabled><br>
<input type="text"value="6" id="avgtime-id" class="averagetime"disabled><br>
<input type="range" name="slider-1" min="0" max="12" value="0" step="1" class="range" id="range-slider"><br>
<input type="text"id="totalavgtime" value="" disabled><br>
<input type="text"id="timetoproduce" value="" disabled><br>
<input type="text"id="timesaving" value="" disabled><br>
You can merge both event handler in one as both are triggering same elements . So , inside this on each iteration get value of range slider and add total to same variable and set them in required input . Now , to subtract them check if the value is not null depending on this take value of input else take 0 to avoid NaN error.
Demo Code :
$(document).ready(function() {
$(".range").on("change", function() {
$(this).next().text($(this).val()) //for output(range)
var selector_next_avg = 0;
var timetoproduce = 0
var checkVal = parseFloat($('.radio-roi:checked').next('input').val()); //radio next input
$('.range').each(function(i) {
var selector_next = parseInt($(".averagetime:eq(" + i + ")").val()) //avg..input
selector_next_avg += parseInt($(this).val()) * selector_next;
timetoproduce += (parseFloat($(this).val()) * checkVal);
})
//set both values
$("#totalavgtime").val(selector_next_avg)
$('#timetoproduce').val(timetoproduce);
total() //call to total..(sub)
})
});
function total() {
var txt1 = $("#totalavgtime").val() != "" ? parseFloat($("#totalavgtime").val()) : 0; //if null take 0
var txt2 = $("#timetoproduce").val() != "" ? parseFloat($("#timetoproduce").val()) : 0;
$("#timesaving").val(txt1 - txt2); //set value
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>
<input type="radio" id="" class="radio-roi" name="plan" value="plus" checked>
<input type="text" value="2.5" id="actualtime2" class="hiden-actual-time" disabled><br>
<input type="radio" id="" class="radio-roi" name="plan" value="pro">
<input type="text" value="3" id="actualtime3" class="hiden-actual-time" disabled><br>
<input type="text" value="6" id="avgtime-id" class="averagetime" disabled><br>
<input type="range" name="slider-1" min="0" max="12" value="0" step="1" class="range" id="range-slider"><output></output><br>
<input type="text" id="totalavgtime" value="" disabled><br>
<input type="text" id="timetoproduce" value="" disabled><br>
<input type="text" id="timesaving" value="" disabled><br>

calculate button question, html and javascript

i just changed my question to show my attempt at it. This is what im trying to do. The XPlevels have a set value, and using that i wanna calculate and display the price
function setprice() {
var val;
var type = document.getElementByName("XP")
if (type[0].checked)
{
var val = 200;
}
else if (type[1].checked)
{
var val = 150;
}
else if (type[2].checked)
{
var val = 100;
}
}
function Calculate() {
var FName = document.getElementById("FName");
var numppl = document.getElementById("numppl");
var Tprice = val * numppl;
window.alert(FName + ", the membership amount is: R " + BasePrice);
<input type="radio" name="XP" value="Novice" onclick="setprice" />Novice
<input type="radio" name="XP" value="Intermediate" onclick="setprice" />Intermediate
<input type="radio" name="XP" value="Expert" onclick="setprice" />Expert
<label for="Members">Number of members</label>
<input id="numppl" type="number" name="Members" size="2" />
<input type="button" value="Calculate fee" onclick="Calculate"/>
You can use onclick event on the Calculate Fee Button to call a JavaScript Function that checks which radio button is selected.
const calculateFee = () => {
let radioButtons = document.querySelectorAll("input");
for(let i=0; i<3; i++){
if(radioButtons[i].checked){
console.log(`Checked Radio Button is : ${radioButtons[i].value}`);
}
}
}
<input type="radio" name="XP" value="Novice" />Novice
<input type="radio" name="XP" value="Intermediate" checked />Intermediate
<input type="radio" name="XP" value="Expert" />Expert
<br />
<label for="Members">Number of members</label>
<input type="number" name="Members" size="2" />
<input type="button" value="Calculate fee" onclick="calculateFee()"/>
This is an edit of your JS code
function setprice() {
var type = document.querySelectorAll('[name="XP"]');
if (type[0].checked) {
var val = 200;
}
else if (type[1].checked) {
var val = 150;
}
else if (type[2].checked) {
var val = 100;
}
return val;
}
function calculate() {
var fName = document.getElementById("FName");
var numppl = document.getElementById("numppl");
var val = setprice();
var tprice = val * numppl.value;
// window.alert(FName + ", the membership amount is: R " + BasePrice);
console.log(tprice);
}
<input type="radio" name="XP" value="Novice" onclick="setprice" />Novice
<input type="radio" name="XP" value="Intermediate" onclick="setprice" />Intermediate
<input type="radio" name="XP" value="Expert" onclick="setprice" />Expert
<label for="Members">Number of members</label>
<input id="numppl" type="number" name="Members" size="2" />
<input type="button" value="Calculate fee" onclick="calculate()" />
This example a more correct approach to what you want
On each radio button, the value is the number (unit price) to be calculated. I have added a data attribute from which to take "Type"
The input named member must be set to a minimum value so that the user cannot set a negative value.
Try this code and if you have any questions I will supplement my answer!
var radio = document.querySelectorAll('.radio');
var number = document.querySelector('.number');
var button = document.querySelector('.button');
var getval;
var datainf;
button.addEventListener('click', function () {
radio.forEach(function (el) {
if (el.checked) {
getval = +el.value;
datainf = el.getAttribute('data');
}
});
var result = getval * number.value;
console.log( 'Quantity: ' + number.value + ' / Type: ' + datainf + ' / The membership amount is: ' + result);
});
<input type="radio" class="radio" name="XP" value="200" data="Novice" />Novice
<input type="radio" class="radio" name="XP" value="150" data="Intermediate" checked />Intermediate
<input type="radio" class="radio" name="XP" value="100" data="Expert" />Expert
<br />
<label for="Members">Number of members</label>
<input type="number" class="number" name="Members" size="2" value="1" min="1" />
<input type="button" class="button" value="Calculate fee" />

How Do I count the selected checkbox in AngularJS?

/**
* #Summary: checkAllConnectedUser function, to create album
* #param: index, productObj
* #return: callback(response)
* #Description:
*/
$scope.shardBuyerKeyIdArray = [];
$scope.countBuyer = 0;
$scope.checkAllSharedBuyer = function(isChecked) {
if (isChecked) {
if ($scope.selectAll) {
$scope.selectAll = false;
} else {
$scope.selectAll = true;
}
angular.forEach($scope.selectedSharedBuyerObjectList, function(selectedBuyer) {
selectedBuyer.select = $scope.selectAll;
//IF ID WILL BE EXIST IN THE ARRAY NOT PSUH THE KEYID
if ($scope.shardBuyerKeyIdArray.indexOf(selectedBuyer.userTypeDto.keyId) == -1) {
$scope.shardBuyerKeyIdArray.push(selectedBuyer.userTypeDto.keyId);
$scope.countBuyer++;
}
});
} else {
$scope.selectAll = false;
//USED FOR UNCHECK ALL THE DATA ONE- BY-ONE
angular.forEach($scope.selectedSharedBuyerObjectList, function(selectedBuyer) {
selectedBuyer.select = $scope.selectAll;
var index = $scope.shardBuyerKeyIdArray.indexOf(selectedBuyer.userTypeDto.keyId);
$scope.shardBuyerKeyIdArray.splice(index, 1);
$scope.countBuyer--;
});
}
}
<div class="checkbox w3-margin" ng-if="selectedSharedBuyerObjectList.length > 0">
<span class="w3-right" ng-if="countBuyer">
<h5>You are selecting {{countBuyer}} buyers!</h5>
</span>
<label>
<input type="checkbox" ng-model="selectAll" ng-click="checkAllSharedBuyer(selectAll)"/>Check All
</label>
</div>
<div id="sharedRow" class="checkbox" ng-repeat="selectedBuyer in cmnBuyer = (selectedSharedBuyerObjectList | filter : userSearchInProduct
| filter : filterUser)">
<label>
<input type="checkbox" ng-model="selectedBuyer.select"
ng-change="selectedSharedBuyer($index, selectedBuyer.select, selectedBuyer.userTypeDto.keyId)"/>
{{selectedBuyer.personName}}
</label>
</div>
I have two list in which i have to count the select all checkbox length as well as single checkbox count my problem if the user un-check the ALL checkbox Checkbox count will be return -- what's the problem in my code?
$(function(){
var count = 0;
$('#sharedRow ').find('input[type=checkbox]').on('change',function(){
$('#msg').text('You are selecting '+$('#sharedRow ').find('input[type=checkbox]:checked').length+' buyers!')
})
$('#chkAll').on('change', function () {
if ($(this).is(':checked')) {
$('#sharedRow ').find('input[type=checkbox]').prop('checked', true);
$('#msg').text('You are selecting '+$('#sharedRow ').find('input[type=checkbox]:checked').length+' buyers!')
}
else {
$('#sharedRow ').find('input[type=checkbox]').prop('checked', false);
$('#msg').text('You are selecting '+$('#sharedRow ').find('input[type=checkbox]:checked').length+' buyers!')
}
});
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<div class="checkbox w3-margin">
<span class="w3-right">
<h5 id="msg" >You are selecting 0 buyers!</h5>
</span>
<label>
<input id="chkAll" type="checkbox" />Check All
</label>
</div>
<div id="sharedRow" class="checkbox">
<label>
<input type="checkbox" value="1 Buyers" />1 Buyers
</label>
<label>
<input type="checkbox" value="2 Buyers" />2 Buyers
</label>
<label>
<input type="checkbox" value="3 Buyers" />3 Buyers
</label>
<label>
<input type="checkbox" value="4 Buyers" />4 Buyers
</label>
<label>
<input type="checkbox" value="5 Buyers" />5 Buyers
</label>
<label>
<input type="checkbox" value="6 Buyers" />6 Buyers
</label>
<label>
<input type="checkbox" value="7 Buyers" />7 Buyers
</label>
<label>
<input type="checkbox" value="8 Buyers" />8 Buyers
</label>
</div>
try this one. is it ok? if not then tell me what's wrong.
if you have a group of checkbox then you can find all selected checkbox.
$('div').find('input[type=checkbox]:checked').length;
If you only need the number
var count = $scope.selectedSharedBuyerObjectList.reduce(function(sum, item) {
return (item.select) ? sum + 1 : sum;
}, 0);
If you need the filtered array
var selected = $scope.selectedSharedBuyerObjectList.filter(function(item) {
return item.select;
});
var count = selected.length;
Or do it using plain old loop
var count = 0;
for (i = 0; i < $scope.selectedSharedBuyerObjectList.length; i++) {
if ($scope.selectedSharedBuyerObjectList.select) count++;
}

Multiply total orders to quantity of order in jquery

I have a jquery that multiplies the price to quantity. Now I wanted to multiply the total of that to how many orders a costumer would place. Where would I insert my multiplication code? Here's how i envisioned the equation would be total=(price*quantity)*numberoforders. Here's a jfiddle of what I cant eloquently explain
Here's my code:
HTML
<form>
<ul>
<li>
<label>
<input type="checkbox" name="drink[]" class="drink" value="DrinkName1" data-price="12" /> Sample Item
<input min="0" max="5" type="number" class="quantity" name="quantity" value="1" />
</label>
</li>
<li>
<label>
<input type="checkbox" name="drink[]" class="drink" value="DrinkName2" data-price="6" /> Sample Item
<input min="0" max="5" type="number" class="quantity" name="quantity" value="1" />
</label>
</li>
<li>
<label>
<input type="checkbox" name="drink[]" class="drink" value="DrinkName3" data-price="4" /> Sample Item
<input min="0" max="5" type="number" class="quantity" name="quantity" value="1" />
</label>
</li>
<li>
<label>
Quantity of Orders
<input min="0" max="5" type="number" class="totalquant" name="quantity" value="1" />
</label>
</li>
</ul>
</form>
<p>Total</p>
<div id="totalDiv">0</div>
Jquery
$('.quantity, .drink').change(calculateTotal);
function calculateTotal() {
var $form = $(this).closest('form'), total = 0;
$form.find('.drink:checked').each(function() {
total += $(this).data('price') * parseInt($(this).next('.quantity').val() || 0, 10);
});
$('#totalDiv').text(total)* parseInt($(this).siblings('.totalquant').val() || 0, 10);
}
Appreciate all the help
I've made some changes on your code here https://jsfiddle.net/k91d23p6/3/
Basically, you have to multiply the total by the totalQuant after the forEach.
//query the DOM once, instead of on every change
var $form = $('form'); //on a real app it would be better to have a class or ID
var $totalQuant = $('.totalquant', $form);
var totalDiv = $('#totalDiv');
$('.quantity, .drink, .totalquant', $form).change(calculateTotal);
function calculateTotal() {
var total = 0;
$form.find('.drink:checked').each(function() {
total += $(this).data('price') * parseInt($(this).next('.quantity').val() || 0, 10);
});
var totalQuant = total * parseInt( $totalQuant.val() || 0, 10);
totalDiv.text(totalQuant);
}

How to calculate sub_total and total_price inputs on onkepress event + JS

How to multiply the Qty textbox with Price textbox then print the output on Subtotal textbox? And then add the grand total of Subtotal textboxes and print the sum on Total Price textbox with keypress event.
<ul>
<li>
Qty<input type="text" name="item_qty0" id="item_qty0" class="item_qty valid" onkeypress="return calProduct(this);" value="1" autocomplete="off" />
Price<input type="text" name="item_price0" id="item_price0" class="item_price valid" onkeypress="return calProduct(this);" value="0" autocomplete="off" />
Subtotal<input type="text" name="item_subtotal0" id="item_subtotal0" class="item_subtotal" disabled="" />
</li>
<li>
Qty<input type="text" name="item_qty1" id="item_qty1" class="item_qty valid" onkeypress="return calProduct(this);" value="1" autocomplete="off" />
Price<input type="text" name="item_price1" id="item_price1" class="item_price valid" onkeypress="return calProduct(this);" value="0" autocomplete="off" />
Subtotal<input type="text" name="item_subtotal1" id="item_subtotal1" class="item_subtotal" disabled="" />
</li>
</ul>
<hr />
<p style="text-align:right;">
Total Price<input name="total_price" maxlength="15" type="text" id="totalPrice" />
</p>
Demo
Here is The working DEMO http://jsfiddle.net/WLSND/
$("input").keyup(function(){
var total = 0;
$('.item_subtotal').each(function (index, element) {
var subtotal = parseInt($(this).parent().find(".item_qty").val())*parseInt($(this).parent().find(".item_price").val()) ;
$(this).val(subtotal);
total = total + subtotal;
});
$("#totalPrice").val(total);
$('input').keyup(function(){
var v = this.value, el = $(this);
if(!isNaN(v)){
var ov = el.siblings('.valid').val();
el.siblings().last().val(v*ov);
$(this).removeClass('nope').trigger('totalChange');
} else {
$(this).addClass('nope');
}
});
$(document).on('totalChange', function(){
var sub1 = parseFloat($('#item_subtotal').val(), 10);
var sub2 = parseFloat($('#item_subtotal2').val(), 10);
$('#totalPrice').val(sub1+sub2);
});
FIDDLE
I also made some changes in the HTML regarding IDs

Categories

Resources