dropdown list with user input calculation - javascript

Basically, I want to use dropdown list value in my calculation with user input, however when i add dropdown value it's either NaN or not giving any value. i did try to calculate based on index select and value change to integer but did not work. any help will be much appreciated
<div id="stock" style="padding-top:15px">
<label>Text Stock</label>
<select name="textStock" id="textStock">
<option value="None">Select Stock</option>
<option value="50gsm">50gsm(£0.10)</option>
<option value="120gsm">120gsm(£0.15)</option>
<option value="150gsm">150gsm(£0.20)</option>
<option value="200gsm">200gsm(£0.30)</option>
<option value="250gsm">250gsm(£0.40)</option>
</select>
</div>
the commented bit is the last working i tried that didn't work
var textStock = new Array();
textStock["None"] = 0;
textStock["50gsm"] = 0.10;
textStock["120gsm"] = 0.20;
textStock["150gsm"] = 0.30;
textStock["200gsm"] = 0.40;
textStock["250gsm"] = 0.50;
/* var stockPrice = 0;
var text_stock = document.getElementById(textStock).value;
var form = document.forms["form"];
var selected = form.elements["textStock"];
var val = textStock[selected.value]; */
var express = document.getElementById("express");
var standard = document.getElementById("standard");
if (express.checked) {
if (productQuantity > 50 && productQuantity < 500) {
discountPrice = (productQuantity * basePrice) * 0.25;
// stockPrice = val * productQuantity;
total = (basePrice * productQuantity) - discountPrice;
//var totalPrice = total + stockPrice;
alert("Express delivery applied, please expect your order within 2 working days\nTotal Price is: £" + total)
}

It's a bit unclear what you are wanting but this should give you the value based on the selected option.
var text_stock = document.getElementById("textStock").value;
var val = textStock[text_stock]; //If "120sgm" is selected, val = 0.2

Related

How to output the currency type next to the converted number

I am trying to get my code to output the currency type name for example EURO, YEN AND USD next to the converted number but I seem to be having trouble, any help would be appreciated.
function tipCalculator() {
var billAmt = document.getElementById("bill").value;
var tipValue = document.getElementById("tipValue").value;
if (billAmt === "" || tipValue == 0) {
alert("Please Enter Value")
return;
}
var total = (billAmt * tipValue);
total = Math.round(total * 100) / 100;
total = total.toFixed(2);
document.getElementById("totalTip").style.display = "block";
document.getElementById("tip").innerHTML = total;
if (document.getElementById("USD")) {
document.getElementById("tip").innerHTML = total + " USD";
}
}
document.getElementById("totalTip").style.display = "none";
document.getElementById("calculate").onclick =
function() {
tipCalculator();
}
<select id="tipValue">
<option value="">--Please choose a currency--</option>
<option value ="1.30353" id="USD">USD</option>
<option value ="1.16158" id="Euro">Euro</option>
<option value ="8.75747" id="Yen">Yen</option>
<option value ="4.98785" id="Zloty">Zloty</option>
</select>
What you need to do is create an array from your currency options (USD, Euro, Yen, Zloty, etc.) and refer to that array instead of "USD" in the following if statement:
if(document.getElementById("USD")){
document.getElementById("tip").innerHTML = total + " USD";
}
Something like this:
if(document.getElementById("currency_array[]")){
document.getElementById("tip").innerHTML = total + " currency_array[]";
}
#elbrant That still has the same problem because you need to know where you are in the array. You need to pass the id to make it dynamic. So, I would make your options into click events so it can pass its id:
document.getElementById("option").onclick =
function() {
tipCalculator(this.id);
}
Don't forget to add the parameter to the function.
In the function, get rid of the if statement and do this:
document.getElementById("tip").innerHTML = total + this.id;

Javascript selection

I have a dropdown list of "Pounds", "grams", "Kilograms" and "Ounces". I want a situation that when I select gram to perform a function, when I input a value in the input field, also when i select pounds i want another function to perform when i input a value in the input field and so on. I have tried it but couldn't get it done.
Here's my code....
HTML
<div id="weight-dropdown">
<h4>Weight Converter</h4>
<select id="select-weight">
<option value="0">...</option>
<option value="1">Pounds</option>
<option value="2">Grams</option>
<option value="3">Kilograms</option>
<option value="4">Ounce</option>
</select>
<input id="input" type="number" placeholder="Enter value...">
</div> <!-- weight dropdown-->
<div id="output">
<div>
<h5>Pounds (lbs) :</h5>
<div id="poundsOutput"></div>
</div>
<div>
<h5>Grams (g) :</h5>
<div id="gramsOutput"></div>
</div>
<div>
<h5>Kilorams (kg) :</h5>
<div id="kgOutput"></div>
</div>
<div>
<h5>Ounce (oz) :</h5>
<div id="ozOutput"></div>
</div>
</div><!--output-->
Javascript
if (document.getElementById("select-weight").selectedIndex = "0"){
document.getElementById("input").addEventListener("input", function(e){
var pounds= e.target.value;
document.getElementById("poundsOutput").innerHTML = pounds
document.getElementById("gramsOutput").innerHTML = pounds/0.0022046;
document.getElementById("kgOutput").innerHTML = pounds/2.2046;
document.getElementById("ozOutput").innerHTML = pounds*16;
})
} else (document.getElementById("select-weight").selectedIndex = "2"){
document.getElementById("input").addEventListener("input", function(e){
var grams= e.target.value;
document.getElementById("poundsOutput").innerHTML = grams*0.0022046;
document.getElementById("gramsOutput").innerHTML = grams;
document.getElementById("kgOutput").innerHTML = grams/1000;
document.getElementById("ozOutput").innerHTML = grams/28.35;
})
}
You assign the input listener based on the input value once , but once assigned it gets always triggered, even if the select changes. May do it the other way round and use a switch:
document.getElementById("input")
.addEventListener("input", function(e){
var input = e.target.value;
switch(document.getElementById("select-weight").selectedIndex){
case 0:
return alert("Please select unit");
break;
case 1 :
var pounds = input;
var grams = input/0.0022046;
var kg = input/2.2046;
var oz = input * 16;
break;
case 2:
var pounds = input * 0.0022046;
var grams = input;
var kg = pounds/2.2046;
var oz = pounds * 16;
break;
case 3:
//...
break;
}
//update DOM with values
document.getElementById("poundsOutput").innerHTML = pounds;
document.getElementById("gramsOutput").innerHTML = grams;
document.getElementById("kgOutput").innerHTML = kg;
document.getElementById("ozOutput").innerHTML = oz;
});
While the upper code is good / understandable, you could use a more shorter approach. You could get the value of the next "row" by dividing through a certain number, and of the previous by multiplying with a certain number. So you could do:
var conversion = [
null,//an endpoint
1,// pounds / this = grams
2,//grams / this = kg
3, //kg/this = oz
null//an endpoint
];
//some pseudocode:
var index = selectWeight.selectedIndex;
var start = event.target.value;
var result = [];
//now multiple from right to left of selected index:
conversion.slice(0,index).reduceRight(function(value,multiplier,i){
result[i] = value;
return value * multiplier;
}, start);
//divide from right to left:
conversion.slice(index-1).reduce(function(value,divider,i){
result[index+i-1] = value;
return value / divider;
},start);
And now weve got our results:
var [pounds,grams,kg,oz] = result;
You're doing a left-hand assignment;
if (document.getElementById("select-weight").selectedIndex = "0"){
while it should be
if (document.getElementById("select-weight").selectedIndex == "0"){
Same applies to other statements.
Use the event onClick for each option and then use their ids to do a factory of weight functions.

Cannot use text in option value with keyup function

I want be able to capture to name=formdesc an option value that is text and not numbers, but I need numbers to calculate price point below. Is there a way to change it, so that it calculates properly (below JS) and capture option values as text only instead numbers (HTML)?
Sample of what I need:
<select id="apparelType" name="formdesc">
<option selected="selected" value="na">Select</option>
<option value="tshirt">T-Shirt</option>
BUT Breakes my JS!
HTML: (what I have now)
<select id="apparelType" name="formdesc">
<option selected="selected" value="na">Select</option>
<option value="0">T-Shirt</option>
<option value="1">Shorts</option>
<option value="2">Hat</option>
<option value="3">Bag</option>
</select>
<input id="numb" type="number" name="formterm">
<id="tot"><Total: $0.00 >
JS:
<script type="text/javascript">// <![CDATA[
//
$(document).ready(function(){
$('#numb').keyup(function(){
var appVal = new Array();
appVal[0] = 15; <--[tshirt]
appVal[1] = 20;
appVal[2] = 25;
appVal[3] = 30;
var cost = 0;
var fmapVal = $('#apparelType').val();
if (fmapVal == 'na')
{ alert ('Please select an apparel type.');
}
else
{
cost = appVal[fmapVal];
};
//alert(cost);
var getNumb = $('#numb').val();
var baseTotal = cost * getNumb;
var getTax = baseTotal * .06;
var getTotal = baseTotal + getTax;
$('#tot').html('Total: $' + getTotal.toFixed(2));
$('#formbal').val(getTotal.toFixed(2));
});
});
// ]]></script>
<form>
<select id="apparelType" name="apparelType">
<option selected="selected" value="na">Select</option>
<option value="0">T-Shirt</option>
<option value="1">Shorts</option>
<option value="2">Hat</option>
<option value="3">Bag</option>
</select>
<label for="numb">Total: <span>$</span></label>
<input id="numb" type="number" name="formterm" value="0.00" >
<input id="pretaxTotal" type="hidden" value="0.00" >
<br>
<textarea id="formdesc" name="formdesc" rows="12" cols="20"></textarea>
</form>
<script type="text/javascript">
$('#apparelType').change(function(){
var apparelType = $('#apparelType');
var fmapVal = apparelType.val();
if (fmapVal == 'na') {
alert('Please select an apparel type.');
} else {
var appVal = [ 15, 20, 25, 30 ];
var description = apparelType.find('option:selected').text();
var cost = appVal[fmapVal];
var pretaxTotal = parseInt($('#pretaxTotal').val());
var subtotal = pretaxTotal + cost;
var updatedTotal = ( subtotal * 1.06 ).toFixed(2);
$('#pretaxTotal').val(subtotal);
$('#numb').val(updatedTotal);
$('#formdesc').append(description + '\n');
}
});
/* The following code is cosmetic. Makes dollar sign appear to be inside the input field */
$('label > span').css('position','relative').css('left','20px').css('font-size','80%');
$('input[type=number]').css('padding-left','15px');
</script>
If you need to take option name then val is not what you need. Instead try this:
var optionName = $('#apparelType').find('option:selected').text();
Hope I understood you correctly (although it's hard).
Could use a function with a case statement to get the cost from passed text strings:
function getVal(value) {
switch(value) {
case 'tshirt':
cost = 15;
break;
case 'shorts':
cost = 15;
break;
case 'hat':
cost = 15;
break;
case 'bag':
cost = 15;
break;
default:
cost = 'Please select an option...';
break;
}
return cost;
}
Then in your if statement use cost = getVal(fmapVal);.

How can my Javascript shopping cart code be improved? Please forgive the raw code [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 9 years ago.
Improve this question
In the last few days I have tried to get my head around Javascript. This is my first proper Javascript and I am wondering if anybody can see anyways that I can improve my code and ultimately my knowledge of Javascript. I appreciate my code thus far may seem a bit raw.
One thing I am stumped at how to finish my 'calcUnitPriceF' function so that I am not creating an array in each product case. These prices will come from a database soon.
The code below I hope is very clear in what it does.
<script type="text/javascript">
function update(){
var total = 0.00;
var calcUnitPrice, quantity;
var myForm = document["getElementById"]("totalform");
var justQuantity = myForm["quantity[]"];
var justPrice = myForm["productPrice[]"];
var unitPrice = myForm["unitPrice[]"];
var linePrice = myForm["linePrice[]"];
for(var i =0; i < justQuantity.length; i++)
{
justQuantity[i].value = Math.floor(justQuantity[i].value);
quantity = justQuantity[i].value;
calcUnitPrice = 0;
if(isNaN(quantity) || quantity < 0) {
justQuantity[i].value ="0";
}
else
{
calcUnitPrice = calcUnitPriceF(justPrice[i].value,quantity);
document.getElementById('unitPrice[' + i + ']').innerHTML = '£' + calcUnitPrice.toFixed(2);
document.getElementById('linePrice[' + i + ']').innerHTML = '£' + (calcUnitPrice * justQuantity[i].value).toFixed(2);
total = (total + (quantity* calcUnitPrice));
}
}
document.getElementById("delivery").innerHTML = "Your Order Delivery is: £2.50";
document.getElementById("Totprice2").innerHTML = "Your Order Total is: £" + total.toFixed(2);
}
function calcUnitPriceF(product,quantity)
{
switch(product)
{
case '0':
return 0;
case '1':
var values = [5, 4 , 15.30 , 10 , 12 ]; // Structure(Exceeding Quantity Price,Quantity Under, Price)
for(var i = 1; i< values.length; i=i+2)
if(quantity < values[i])
return values[i+1];
return values[0];
case '2':
return 75;
}
}
</script>
<body>
<form id="totalform">
<select id ="productPrice[]" onchange="update()">
<option value="0">Please Select One</option>
<option value="1">Product 1</option>
<option value="2">Product 2</option>
</select>
QUANTITY <input type = "text" id = "quantity[]" onChange="update()" >
UNIT PRICE <p id="unitPrice[0]" style="display:inline;">£0.00</p>
LINE PRICE <p id="linePrice[0]" style="display:inline;">£0.00</p><br />
<select id="productPrice[]" onchange="update()">
<option value="0">Please Select One</option>
<option value="1">Product 1</option>
<option value="2">Product 2</option>
</select>
QUANTITY <input type = "text" id = "quantity[]" onChange="update()" >
UNIT PRICE <p id="unitPrice[1]" style="display:inline;">£0.00</p>
LINE PRICE <p id="linePrice[1]" style="display:inline;">£0.00</p><br />
<span id ="delivery">Your Order Delivery is: £0.00</span><br />
<span id ="Totprice2">Your Order Total is: £0.00</span>
</form>
The number one thing I would do is change the JS approach.
var project = {};
project.ShoppingCart = function() {
this.total = 0;
this.justQuantity = ...;
this.currentQuantity = 0;
};
/**
* Updates the current quantity in the shopping cart.
* #param {!number} quantity The quantity to update with.
* #return {void} nothing.
*/
project.ShoppingCart.prototype.updateQuantity = function(quantity) {
// this is how to check for a number properly.
if (!isNaN(quantity) && parseFloat(quantity) && isFinite(quantity)) {
this.currentQuantity = quantity;
} else {
console.log("Invalid quantity");
};
};
Now in order to use the above.
var shoppingCart = new project.ShoppingCart();
Look at Object Oriented Javascript, how to properly use that, stop poluting the global namespace and randomly writing functions, comment your code and validate things properly.

HTML Connected dropdown (more than one)with number as value

Basically, I want to create more then 1, dropdowns, which contains numbers as value eg.
<select id="dp1">
<option value='op1'>1</option>
<option value='op2'>2</option>
<option value='op3'>3</option>
</select>
<select id="dp2">
<option value='op1'>1</option>
<option value='op2'>2</option>
<option value='op3'>3</option>
</select>
<select id="dp3">
<option value='op1'>1</option>
<option value='op2'>2</option>
<option value='op3'>3</option>
</select>
this is just one dropdown. lets say I have 3 dropdown lists with same numbers with different default value eg. dp1 -> 1, dp2 -> 2, dp3 -> 3 . So, Now if user changes value of dp3 to 1 the value of other dropdown list should get change automatically as per sequence like dp1 -> 2 and dp2 -> 3.
if i explain it with other example if user changes value of dp3 to 2 the value dp1 should not change and value of dp2 -> 3should change.
How is it possible to do using Javascript / jquery. (I am using php to populate dropdown from database)
Thank you in advance.
if you just want to change the previous dropdownlists buy changing the current dropdownlist maybe this sample code can help you :
$("select").change(function(){
var selectValue = $(this).val();
var toRemove = 'op';
var value = selectValue.replace(toRemove,'');
var selectId = $(this).attr('id');
var toRemove = 'dp';
var id = selectId.replace(toRemove,'');
id = id-1;
for(var i = id; i>=1; i--){
value = value -1;
var newValue = "op"+value;
$("#dp"+i).val(newValue);
}
});
If the data you're using is really just numeric, then something like this will work. Click here for a jsfiddle example that demonstrates the behavior I think you're looking for.
<select id="dp1" class="dropdown"></select>
<select id="dp2" class="dropdown"></select>
<select id="dp3" class="dropdown"></select>
<script type="text/javascript">
var values = [1, 2, 3];
$(function() {
initDropdowns();
$('select.dropdown').change(function() {
setDropdownValues($(this).attr('id'));
});
});
function initDropdowns() {
var optionsHtml = '';
for(var i = 0; i < values.length; i++) {
var value = values[i];
optionsHtml += '<option value="' + value + '">' + value + '</option>';
}
$('select.dropdown').append(optionsHtml);
setDropdownValues();
}
function setDropdownValues(excludeListId) {
var valuesClone = values.slice();
var $dropdowns = $('select.dropdown');
if(excludeListId) {
valuesClone.splice(Number($('#' + excludeListId).val()) - 1, 1);
}
$('select.dropdown').each(function() {
if($(this).attr('id') !== excludeListId) {
$(this).val(valuesClone[0]);
valuesClone.splice(0, 1);
}
});
}
</script>

Categories

Resources