Calculate tax rate with selects using javascript - javascript

I've been using code from this question to create something very similar, the only thing I want to change is the calculation to get a different total result.
In that example they take the first value times the other and then echo out the result.
Taking the first value times the second works very well, but when I try to make the calculation more advanced it all fails.
I want to be able to make the following equation with the selected values:
var total = ((firstSelect*secondSelect)-firstSelect*0,68)*300;
alert(total);
I've also tried the following and this too fails:
var oppa = firstSelect * rate;
var gagnam = secondSelect * 0.68;
var style = oppa - gagnam;
var total = style * 300;
alert(total);
Currently my HTML looks like this:
<p>Number of sales</p>
<select name="firstSelect" id="firstSelect" class="DoPricing">
<option value="15">15</option>
<option value="20">20</option>
<option value="25">25</option>
<option value="30">30</option>
<option value="35">35</option>
<option value="40">40</option>
<option value="45">45</option>
<option value="50">50</option>
<option value="55">55</option>
<option value="100">100</option>
<option value="150">150</option>
</select>
<p>Times rate</p>
<select name="secondSelect" id="secondSelect" class="DoPricing">
<option value="0.99">0.99</option>
<option value="1.15">1.15</option>
<option value="1.5">1.5</option>
<option value="2">2</option>
<option value="2.5">2.5</option>
<option value="3">3</option>
</select>
<br>
<br>
<input type="submit" name="submit" value="submit" id="submit">
and my JS
function calc() {
var total,
nSales,
rate;
var nSales = document.getElementsByName("firstSelect")[0].value;
var rate = document.getElementsByName("secondSelect")[0].value;
var oppa = nSales * rate;
var gagnam = rate * 0.68;
var style = oppa - gagnam;
var total = style * 300;
alert(total);
}
window.onload = function () {
document.getElementById("submit").onclick = calc;
};
How would I go about to accomplish this?

You have the onclick handler inside the calc() function, you should have it outside so it add the event listener on windows.onload
function calc() {
var total,
nSales,
rate;
var nSales = document.getElementsByName("firstSelect")[0].value;
var rate = document.getElementsByName("secondSelect")[0].value;
var oppa = nSales * rate;
var gagnam = nSales* 0.68; //changed to nSales
var style = oppa - gagnam;
var total = style * 300;
alert(total);
};
window.onload = function () {
document.getElementById("submit").onclick = calc;
}
Demo here

Related

Call array by using variable value of option selected

I have some arrays defined in js, I want to use the variable's value from selected option to select which array should I select.
I tried using this:
//code HTML
<select id="bank">
<option value="ACB">ACB</option>
<option value="SCB">SCB</option>
</select>
<select id="month">
<option value="1">1 month</option>
<option value="2">2 month</option>
<option value="3">3 month</option>
</select>
<p id="demo"></p>
// JS
var ACB = ["1%", "2%", "3%"];
var SCB = ["4%", "5%", "6%"];
selectElement = document.querySelector('#bank');
var a = selectElement.value; // a = ACB
selectElement = document.querySelector('#month');
var b = selectElement.value; // b = 1
document.getElementById("demo").innerHTML = a[b]; // I was hoping result is "1%"
Any suggestions are appreciated!
Thanks so much!
According to your code, you would never get the expected result. Because you are taking a[b]. But here a value type would be string and when you use indexing on strings then you will get its char at that specific index.
You can achieve the expected result as
1) Create a dict which contains both ACB and SCB reference
const dict = { ACB, SCB };
2) You can get the array's value from dict as
p.textContent = dict[a][b - 1];
3) b index should start with zero, so to get the first result you should subtract -1 from b.
// JS
var ACB = ["1%", "2%", "3%"];
var SCB = ["4%", "5%", "6%"];
const dict = { ACB, SCB };
const bankEl = document.querySelector( '#bank' );
const monthEl = document.querySelector( '#month' );
const p = document.getElementById( "demo" );
const a = bankEl.value; // a = ACB
const b = monthEl.value; // b = 1
p.textContent = dict[a][b - 1]; // I was hoping result is "1%"
<select id="bank">
<option value="ACB">ACB</option>
<option value="SCB">SCB</option>
</select>
<select id="month">
<option value="1">1 month</option>
<option value="2">2 month</option>
<option value="3">3 month</option>
</select>
<h1 id="demo"></h1>

JQuery add another value to each array item & sum

I currently have an array that is populated by changing the value/option of many select fields. E.g. If two select fields are in the dom and the options selected are 2 & 3 then the array would look like this - Array [ "2", "3" ]
Each select has a data attribute data-ticketprice which I would like to bind to each of the option values. So I can get the sum of both of the numbers e.g.
data attribute = 100
Select option value = 5
Sum = 100 x 5;
HTML -
<select class="ticket-qty" data-ticketprice="280.88" name="34">
<option value="0">0 Tickets</option>
<option value="1">1 Ticket</option>
<option value="2">2 Tickets</option>
<option value="3">3 Tickets</option>
<option value="4">4 Tickets</option>
<option value="5">5 Tickets</option>
</select>
<select class="ticket-qty" data-ticketprice="390" name="39">
<option value="0">0 Tickets</option>
<option value="1">1 Ticket</option>
<option value="2">2 Tickets</option>
<option value="3">3 Tickets</option>
<option value="4">4 Tickets</option>
<option value="5">5 Tickets</option>
</select>
Current jQuery -
//When select is changed update value to array
$('select.ticket-qty').on('change', function (e) {
//Map the values for the array
var arr = $('select.ticket-qty').map(function(){
return this.value
}).get()
//This sums the all the select options (not what I want)
var total = 0;
for (var i = 0; i < arr.length; i++) {
total += arr[i] << 0;
}
console.log(total);
});
You need to fill the array you build with map() with the selected quantity multiplied by the cost per item, which you can retrieve from the data attribute. From there you can use reduce() to sum up all values in the array. Something like this:
$('select.ticket-qty').on('change', function(e) {
var arr = $('select.ticket-qty').map(function() {
var cost = $(this).data('ticketprice');
var qty = $(this).val();
return cost * qty;
}).get();
var total = arr.reduce((a, b) => a + b, 0);
console.log(total);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="ticket-qty" data-ticketprice="280.88" name="34">
<option value="0">0 Tickets</option>
<option value="1">1 Ticket</option>
<option value="2">2 Tickets</option>
<option value="3">3 Tickets</option>
<option value="4">4 Tickets</option>
<option value="5">5 Tickets</option>
</select>
<select class="ticket-qty" data-ticketprice="390" name="39">
<option value="0">0 Tickets</option>
<option value="1">1 Ticket</option>
<option value="2">2 Tickets</option>
<option value="3">3 Tickets</option>
<option value="4">4 Tickets</option>
<option value="5">5 Tickets</option>
</select>
You should note that this can all be done in a single loop, however I am assuming you're building the array of individual totals for use elsewhere in your UI.
So how far I understand is, you want to multiply the selected value with the given data attribute on Select?
Here is sample code for getting Array of All selected values. And how to calculate the value you posted.
var array = [];
var i =0;
$('select.ticket-qty').on('change', function (e) {
// Get value of all selects in array.
$('select.ticket-qty').each(function(){
array[i] = $(this).val();
i++;
});
//calculate Sum ?
var data_attribute = $(this).data("ticketprice");
SelectedOptionValue = = $(this).val();
Sum = parseFloat(data_attribute)* parseInt(SelectedOptionValue);
});
Vanilla JS
const SELECTS = document.querySelectorAll('select.ticket-qty')
const LOG_SUM = e => {
const ticketPrice = e.target.getAttribute('data-ticketPrice')
const multiplier = e.target.value
const SUM = (+ticketPrice * +multiplier)
console.log(SUM)
}
SELECTS.forEach(select => {
select.addEventListener('change', e => {
LOG_SUM(e)
})
})
jQuery
$('select.ticket-qty').on('change', e => {
const ticketPrice = $(e.target).attr('data-ticketPrice')
const multiplier = e.target.value
const SUM = (+ticketPrice * +multiplier)
console.log(SUM)
});
Notice how i prepend the + operator to the ticketPrice & multiplier constants... this is because attr && value are returning Strings and the + operator converts numbers of type String into numbers of type Number
You can use some jQuery plugins to populate and reduce the select boxes.
(function($) {
$.reduce = function(arr, fn, initial) {
initial = typeof initial === 'undefined' ? 0 : initial;
$.each(arr, function(i, v) {
initial = fn(initial, v, i);
});
return initial;
};
$.fn.reduce = function(fn, initial) {
return $.reduce(this, fn, initial);
};
$.fn.populateCombo = function(opts) {
let data = opts.data || Array.apply(null, {length: opts.range || 0}).map(Number.call, Number);
return this.append(data.map(x => $('<option>')
.text(opts.textFn ? opts.textFn(x) : x)
.val(opts.valFn ? opts.valFn(x) : x)));
};
})(jQuery);
$('.ticket-qty').each((i, combo) => $(combo).populateCombo({
range : 6, textFn: v => v + ' Tickets'
}));
$('select.ticket-qty').on('change', function(e) {
var total = $('select.ticket-qty').reduce(function(result, item) {
return result + $(item).data('ticketprice') * $(item).val();
}, 0);
console.log('$' + total.toFixed(2));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select class="ticket-qty" data-ticketprice="280.88" name="34"></select>
<select class="ticket-qty" data-ticketprice="390" name="39"></select>

select.getElementsByTagName except for a certain option

Option List
I have an problem where my Random Option Picker picks a certain option that I don't want. How do I mitigate this?
var select = document.getElementById('edit-categories');
var items = select.getElementsByTagName('option');
var index = Math.floor(Math.random() * items.length + 1);
return select.selectedIndex = index;
The option that I want my random picker to ommit is : value="_none"
Use querySelectorAll along with :not and an attribute selector:
var items = select.querySelectorAll('option:not([value="_none"])');
var select = document.querySelector('select');
var items = select.querySelectorAll('option:not([value="_none"])');
console.log(items);
<select>
<option value="_none">--</option>
<option value="water">Water</option>
<option value="waste">Waste</option>
</select>
As an alternative, you can also use Array.prototype.filter (since It's a lot easier to pollyfil filter than the [not] selector):
var opts = [].filter.call(document.getElementById('edit-categories').options, function(opt){return opt.value != '_none'})
console.log(opts);
<select id="edit-categories">
<option value="_none">None
<option value="foo">Foo
<option value="foo">Bar
</select>
You can add a while loop just before setting the index :
var select = document.getElementById('edit-categories');
var items = select.getElementsByTagName('option');
var index = Math.floor(Math.random() * items.length);
while (items[index].value == '_none') {
index = Math.floor(Math.random() * items.length);
}
select.selectedIndex = index;
<select id="edit-categories">
<option value="0">0</option>
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="_none">none</option>
<option value="4">4</option>
</select>

jQuery looping through an object array

I have the following HTML and JS, I am trying to only display elements if they match the criteria selected in the <select> tags. I am fairly sure that my IF statement currently would not achieve what I am trying to do even if it did work, however I am struggling to think of the logic for this.
HTML:
<select id="price-from" class="form-control">
<option selected value="£500">£500</option>
<option value="1000">£1,000</option>
<option value="2000">£2,000</option>
<option value="3000">£3,000</option>
<option value="4000">£4,000</option>
<option value="5000">£5,000</option>
<option value="10000">£10,000</option>
<option value="20000">£20,000</option>
</select>
<p>To</p>
<select id="price-to" class="form-control">
<option value="500">£500</option>
<option value="1000">£1,000</option>
<option value="2000">£2,000</option>
<option value="3000">£3,000</option>
<option value="4000">£4,000</option>
<option value="5000">£5,000</option>
<option value="10000">£10,000</option>
<option selected value="20000">£20,000</option>
</select>
JavaScript:
$(document).ready(function(){
var product1 = {title:"Cute Gnome", type:"Cute", price:"3999"};
var product2 = {title:"Funny Gnome", type:"Funny", price:"5999"};
var product3 = {title:"Seasonal Gnome", type:"Seasonal", price:"12999"};
var product4 = {title:"Horror Gnome", type:"Horror", price:"7999"};
var productArray = [
product1, product2, product3, product4
];
var len = productArray.length;
for (var i = 0; i < len; i++) {
if ($("#price-from").val() < productArray[i].price && $("#price-to").val() > productArray[i].price){
//Loop through code and only output objects between both price criteria
}
}
});
You need to bind the change event to select elements. Additionally you should to convert string to Number before comparison. use .filter()
$('select').on('change', function() {
var priceFrom = +$("#price-from").val(); //Convert value to Number
var priceTo = +$("#price-to").val(); //Convert value to Number
//Filter the elements which matches the condition
var matchingElemets = productArray.filter(function(pd) {
var p = +pd.price; //Convert value to Number
return p >= priceFrom && p <= priceTo;
});
console.clear();
console.log(matchingElemets);
});
$(document).ready(function() {
var product1 = {
title: "Cute Gnome",
type: "Cute",
price: "3999"
};
var product2 = {
title: "Funny Gnome",
type: "Funny",
price: "5999"
};
var product3 = {
title: "Seasonal Gnome",
type: "Seasonal",
price: "12999"
};
var product4 = {
title: "Horror Gnome",
type: "Horror",
price: "7999"
};
var productArray = [
product1, product2, product3, product4
];
$('select').on('change', function() {
var priceFrom = +$("#price-from").val(); //Convert value to Number
var priceTo = +$("#price-to").val(); //Convert value to Number
var matchingElemets = productArray.filter(function(pd) {
var p = +pd.price; //Convert value to Number
return p >= priceFrom && p <= priceTo;
});
console.clear();
console.log(matchingElemets)
});
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="price-from" class="form-control">
<option selected value="£500">£500</option>
<option value="1000">£1,000</option>
<option value="2000">£2,000</option>
<option value="3000">£3,000</option>
<option value="4000">£4,000</option>
<option value="5000">£5,000</option>
<option value="10000">£10,000</option>
<option value="20000">£20,000</option>
</select>
<p>To</p>
<select id="price-to" class="form-control">
<option value="500">£500</option>
<option value="1000">£1,000</option>
<option value="2000">£2,000</option>
<option value="3000">£3,000</option>
<option value="4000">£4,000</option>
<option value="5000">£5,000</option>
<option value="10000">£10,000</option>
<option selected value="20000">£20,000</option>
</select>
Code below add it to the onchange Attribute on both of the selects and you have a Framework Independent solution that Returns the list.
Ofcourse you will have to add your own logic to Change displayed products.
Do note that haveing a .ready doesnt really do annything here since it is (should be) an Event driven Action.
function filter()
{
//reduces calls to DOM in for loop
var min = document.getElementById("price-from").value;
var max = document.getElementById("price-to").value;
var length = productArray.length;
var products = [];
for (var i = 0; i < length; i++) {
if (min <= productArray[i].price && max > productArray[i].price) {
products.push(productArray[i]);
}
}
return products;
}
You presumably want to do this whenever one of the select boxes is changed, so the thing to do is hook into the change event on both and run your code. You dont specify what you mean by "output" so I'll just output to the console.
var product1 = {title:"Cute Gnome", type:"Cute", price:"3999"};
var product2 = {title:"Funny Gnome", type:"Funny", price:"5999"};
var product3 = {title:"Seasonal Gnome", type:"Seasonal", price:"12999"};
var product4 = {title:"Horror Gnome", type:"Horror", price:"7999"};
var productArray = [
product1, product2, product3, product4
];
$('select').on('change',function(){
var from = parseInt($('#price-from').val(),10);
var to = parseInt($('#price-to').val(),10);
var matches = productArray.filter(function(x){
var price = parseInt(x.price,10);
return from <= price && to >= price;
});
console.clear();
console.log(matches);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<select id="price-from" class="form-control">
<option selected value="£500">£500</option>
<option value="1000">£1,000</option>
<option value="2000">£2,000</option>
<option value="3000">£3,000</option>
<option value="4000">£4,000</option>
<option value="5000">£5,000</option>
<option value="10000">£10,000</option>
<option value="20000">£20,000</option>
</select>
<p>To</p>
<select id="price-to" class="form-control">
<option value="500">£500</option>
<option value="1000">£1,000</option>
<option value="2000">£2,000</option>
<option value="3000">£3,000</option>
<option value="4000">£4,000</option>
<option value="5000">£5,000</option>
<option value="10000">£10,000</option>
<option selected value="20000">£20,000</option>
</select>
Roughly what this code is doing is as follows
var from = parseInt($('#price-from').val(),10);
var to = parseInt($('#price-to').val(),10);
These two lines take the values of your two select boxes, and parse their value to an integer. See parseInt
var matches = productArray.filter(function(x){
var price = parseInt(x.price,10);
return from <= price && to >= price;
});
This line uses filter to get the items from your original list which fall within the range of prices selected. See Array.filter
console.clear();
console.log(matches);
These lines simply clear and then output the items from the array which match your prices to the console. You could easily iterate over this list and output to the page iif required.

Need Value from Simple Javascript Addition Multiplication

I'm not sure what I am doing wrong, but I am just trying to get a total price to display after you make a selection. I want to take the value of the selection and multiply it by 100 and then use the updatetotal function to display the total.
// Collect Data & Prices To Update Dynamic Prices
var pricechecking=document.getElementById('howmanyaccts')value.trim();
var pricepaypal=document.getElementById('howmanyacctspaypal')value.trim();
var pricecheck = pricechecking * 100;
var pricepay = pricepaypal * 100;
function updateTotal() {
var ThePrice = pricecheck + pricepay;
$('#TotalPrice').text('$' + ThePrice + '.00');
}
$(function () { $('.DoPricing').click(updateTotal); });
MY HTML IS:
<form action="http://linktomyactionpage" method="post" >
<p>How many accounts to pay by check?</p>
<select name="howmanyaccts" id="howmanyaccts" class="DoPricing">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<p>How many accounts to pay by paypal?</p>
<select name="howmanyacctspaypal" id="howmanyacctspaypal" class="DoPricing">
<option value="1">1</option>
<option value="2">2</option>
<option value="3">3</option>
<option value="4">4</option>
<option value="5">5</option>
</select>
<p>Total: <span id="TotalPrice">$0.00</span></p>
<input type="submit" name="submit" value="submit">
</form>
What if I simplified the code? Brought the 00.00 to the text and no multiplication?
// Collect Data & Prices To Update Dynamic Prices
var pricechecking=document.getElementById('howmanyaccts').value.trim();
var pricepaypal=document.getElementById('howmanyacctspaypal').value.trim();
function updateTotal() {
var ThePrice = pricechecking + pricepaypal;
$('#TotalPrice').text('$' + ThePrice + '00.00');
}
$(function () { $('.DoPricing').click(updateTotal); });
HERE IS WHAT I GOT TO WORK:
// Collect Data & Prices To Update Dynamic Prices
var pricechecking=document.getElementById('howmanyaccts').value.trim();
var pricepaypal=document.getElementById('howmanyacctspaypal').value.trim();
function updateTotal() {
var pricecheck = parseInt($('#howmanyaccts').val(), 10);
var pricepay = parseInt($('#howmanyacctspaypal').val(), 10);
var ThePrice = pricecheck + pricepay;
$('#TotalPrice').text('$' + ThePrice + '00.00');
}
$(function () { $('.DoPricing').click(updateTotal); });
I think you want to do something like this : http://jsfiddle.net/F3HbJ/
$(function () {
$('.DoPricing').change(function () {
var total = 0;
$('.DoPricing').each(function () {
total += parseInt($(this).val()) * 100;
});
$('#TotalPrice').html('$' + total);
});
});
The event handler is .change() for a select. Then you loop through the parseInt values of each select that you multiply by 100.
Here is working DEMO
use like this :
$(document).ready(function () {
var pricechecking = $($("#howmanyaccts")[0].selectedOptions).attr("value");
var pricepaypal = $($("#howmanyacctspaypal")[0].selectedOptions).attr("value");
function updateTotal() {
var pricecheck = parseInt($('#howmanyaccts').val(), 10);
var pricepay = parseInt($('#howmanyacctspaypal').val(), 10);
var ThePrice = pricecheck + pricepay;
$('#TotalPrice').text('$' + ThePrice + '00.00');
}
$('.DoPricing').change(updateTotal);
});

Categories