Javascript selection - javascript

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.

Related

Add array values without clearing previous value using javascript

I have a password generator which works fine. But need a little change. The below image shows
Once I click the "Generate Password" button it generates one password.
Required: When I click the button again, I need to have another password generated below without clearing the previous one. Tried a couple of variations in loop but did not work.
**passGen.js**
function passGen() {
var Generator = {};
Generator.generateMnemonic = function(length, num_length, mixcase) {
var ret = '';
var vowels = 'aeioe';
var consonants = 'bcdfghklmnpqrstvwxzy';
if (mixcase) {
vowels += vowels.toUpperCase();
consonants += consonants.toUpperCase();
}
vowels = vowels.split('');
consonants = consonants.split('');
for(var i = 0; i < length / 2; i++) {
ret += vowels.getRandom();
ret += consonants.getRandom();
}
if (!num_length) return ret;
var pos = $random(2, length - 2 - num_length);
return ret.substr(0, pos) + $random(Math.pow(10, num_length - 1), Math.pow(10, num_length) - 1) + ret.substr(pos + num_length);
};
var observe = new Observer('#generator-length, #generator-num_length, #generator-mixcase, #generator-amount', function(values) {
var length = values[0].toInt();
var num_length = values[1].toInt();
var mixcase = values[2].toInt();
var amount = values[3].toInt();
// Fill passwords in a loop
var words = [];
for (var i = 0; i < amount; i++) {
words.push(Generator.generateMnemonic(length, num_length, mixcase) );
}
// Get the output area
var output = $('generator-output');
// Output it and highlight it so users will notice the update
output.value = words.join("\n");
output.getParent().highlight('#ff8', '#fff');
}, {
// periodical: 1000 // interval in ms
});
// To fill in the first values
observe.fire();
}
**Part of Hmtl**
<script type="text/javascript" src="passGen.js"></script>
<span>How many passwords:</span>
<br>
<select name="amount" id="generator-amount">
<option value="1" selected>1</option>
<option value="5">5</option>
<option value="10">10</option>
<option value="50">50</option>
<option value="100">100</option>
</select>
</label>
<input type="button" name="button" value="Generate Password" onclick="passGen();">
<label>
<br>
<span>Your passwords:</span>
Do something along these lines: (small example to give the feel) with a static variable.
function passGen() {
if ( typeof passGen.words == 'undefined' ) { /* It has not been called do initialization*/
passGen.words = [];}//else previous passwords persist, and you push, onto them.
passGen.words.push("Hello");
alert(passGen.words);
}
passGen();
passGen();
In your case keep my initial if, remove your line
var words = [];
and prepend passGen. to your words.push and words.join
adapted from Static variables in JavaScript

Calculate the price of the items, depending on its quantity

I'm trying to make block with the prices. The unit price varies depending on its quantity of units. For example:
Quantity — Price for each
1____________________$110
10___________________$105
20___________________$100
...
Number of items:__
Total:
Price for each:
There is a need to write a the text field into which the user enters the number of items, and everything is recalculating and summing on the fly.
Here is my realization of this task:
var price1 = 110,
price2 = 105,
price3 = 100,
qty1 = 1,
qty2 = 10,
qty3 = 20;
function conversion(val) {
var div = document.getElementById("div"),
price = document.getElementById("price");
if (isNaN(val)) {
div.innerHTML = "";
price.innerHTML = "";
} else {
switch (true) {
case (val <= 0):
{
div.innerHTML = "";
price.innerHTML = "";
break;
}
case (val >= qty1 && val < qty2):
{
div.innerHTML = val * price1;
price.innerHTML = price1;
break;
}
case (val >= qty2 && val < qty3):
{
div.innerHTML = val * price2;
price.innerHTML = price2;
break;
}
case (val >= qty3):
{
div.innerHTML = val * price3;
price.innerHTML = price3;
break;
}
}
}
}
<div>
Quantity — Price for each
</div>
<div>
<div>1 — $110</div>
<div>10 — $105</div>
<div>20 — $100</div>
</div>
<div>
Number of items:
<div>
<input id="txt" onblur="conversion(this.value)" onchange="conversion(this.value)" onkeypress="conversion(this.value)" onkeyup="conversion(this.value)" type="number">
</div>
</div>
<div>
Total:
<div id="div"></div>
</div>
<div>
Price for each:
<div id="price"></div>
</div>
How it can be properly implemented, taking into account the fact that the lines with the quantity and unit price can be from one to infinity (values are taken from the database)?
I think it is possible to record the price and quantity in data-atributes and parse it with JS. Like this:
...
<div data-quantity="10" data-price="105">
<span class="quantity">10</span>
<span class="price">105</span>
</div>
...
Thanks!
Using the data attribute is indeed a solution:
console.log(document.getElementById("test").dataset)
<div data-quantity="10" data-price="105" id="test">
<span class="quantity">10</span>
<span class="price">105</span>
</div>
It's not fully compatible with previous IE version though, so be careful with it.
I would however suggest that you look for a way of moving your calculations away from the DOM to speed up your calculations.
For instance, parsing the data to a JavaScript object and doing the calculations there would save you some DOM trips and thus speed:
console.clear();
//markup for product
function Product(name) {
return {
//Name of product
name : name,
//List of price ranges (populated later)
prices : [
],
//method for adding a price
newPrice : function newPrice(quantity, cost) {
//Push new price unto list
this.prices.push({
quantity : quantity,
cost : cost
});
//Sort list
this.prices = this.prices.sort(function (a, b) {
return a.quantity - b.quantity
});
},
//Get the price for a variable quantity of this product
get : function (quantity) {
//Loop through prices to find the most matching
var price = 0;
for (var i = 0; i < this.prices.length; i++) {
if (this.prices[i].quantity <= quantity) {
price = this.prices[i].cost;
} else {
break;
}
}
console.log('price per unit:', price, 'price for all', quantity, 'units:', price * quantity)
}
};
} //Make an instance
var myHotProduct = new Product('Fancy pants');
//Add some prices
myHotProduct.newPrice(0, 110);
myHotProduct.newPrice(10, 105);
myHotProduct.newPrice(20, 100);
//get some quantities
myHotProduct.get(0);
myHotProduct.get(1);
myHotProduct.get(9);
myHotProduct.get(10);
myHotProduct.get(19);
myHotProduct.get(20);
//Log everything we know about our product
console.log(myHotProduct);
Now you can get your prices as arrays and modify them outside of the limitations of data-.

dropdown list with user input calculation

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

Text Box Event Javascript [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 8 years ago.
Improve this question
I'm a noobie and I need some help with changing events in textbox.
Here's the code I am working with:
<body>
<form action="#">
<input type="text" id="begin" /> Apple
=
<input type="text" id="done" />
<select id="newValue" onchange = "function()">
<option value="a">Apple</option>
<option value="b">Blueberry</option>
<option value="c">Cheese</option>
</select>
<p id = "weight"></p>
</form>
<script>
var apple = document.getElementById('begin'),
choice = document.getElementById('done');
apple.onkeyup = function(){
var temp = document.getElementById("newValue").value;
choice.value = this.value * 1; //if apple
choice.value = this.value * 2; //if blueberry
choice.value = this.value * 3; //if cheese
}
</script>
</body>
I have two text boxes. The left text box ('begin') will accept the weight of apple. But the right box ('done') should change the number value depending on what the user chooses form the drop-down text list.
My
apple.onkeyup = function(){
is not doing the right thing. If I give the value of '2' to the left text box,no matter what I choose in the dropdown list, it will return 2 * 3 = 6, meaning it skips everything in the function and evaluates only the last statement.
choice.value = this.value * 3; /*if cheese
How I want it to work is:
Left Box : 2 Right Box : 2 (if apple was chosen)
Left Box : 2 Right Box : 4 (if blueberry was chosen)
I'm sure I need a few 'if statements' to determine which output choice was chosen, something along the lines of
if(temp = Apple){
choice.value = this.value * 1;
}else if(temp = Blueberry){
choice.value = this.value * 2;
}
}
The value in Right Box should also change as the user chooses a different item from the list..
Although I'm not sure if that's the right approach/syntax.
I think this may be what you are looking for, here is a fiddle.
Remove the onchange from your newValue selection and set it in your JavaScript, just like you are doing with your onkeyup function for apple. In your code above, your are calling function() which will likely just cause errors. function() represents an anonymous function, you need to name your function with the syntax function name() if you'd like to call it in this way. However, since you are already setting onkeyup from your JavaScript, you might as well set onchange from the same place in this case.
Then change your JavaScript to this:
var apple = document.getElementById("begin"),
choice = document.getElementById("done"),
fruits = document.getElementById("newValue");
// This function properly sets the done field.
var setDone = function() {
var newVal = document.getElementById("newValue").value;
if (newVal == "a") {
choice.value = apple.value * 1; //if apple
} else if (newVal == "b") {
choice.value = apple.value * 2; //if blueberry
} else if (newVal == "c") {
choice.value = apple.value * 3; //if cheese
} else {
alert("I couldn't find that value!");
}
}
apple.onkeyup = setDone;
fruits.onchange = setDone;
I made your anonymous function into a named variable ,added if statements to check for the value of newValue and set the value of apple appropriately.
Then I set the onkeyup and onchange events for apple and the new variable I created for your selector, fruits.
If you have any questions about how any of this works, feel free to ask in the comments below.
Try this - I'm not sure if I got my apples and blueberries in the right order, but it looks to work OK:
var apple = document.getElementById('begin'),
choice = document.getElementById('done');
apple.onkeyup = function(){
var temp = document.getElementById("newValue").value;
if (temp == 'a') {
choice.value = this.value * 1;
}
if (temp == 'b') {
choice.value = this.value * 2;
}
if (temp == 'c') {
choice.value = this.value * 3;
}
}
FIDDLE
Your code :
var temp = document.getElementById("newValue").value;
choice.value = this.value * 1; //if apple
choice.value = this.value * 2; //if blueberry
choice.value = this.value * 3; /*if cheese
is equal to :
var temp = document.getElementById("newValue").value;
choice.value = this.value * 3;
you repeat assign value to choice.value, so the finally result is :
choice.value = this.value * 3;
you should change the code :
<select id="newValue" onchange = "function()">
<option value="1">Apple</option>
<option value="2">Blueberry</option>
<option value="3">Cheese</option>
</select>
to :
<select id="newValue" onchange = "function()">
<option value="a">Apple</option>
<option value="b">Blueberry</option>
<option value="c">Cheese</option>
</select>
and then change the code :
var temp = document.getElementById("newValue").value;
choice.value = this.value * 1; //if apple
choice.value = this.value * 2; //if blueberry
choice.value = this.value * 3; /*if cheese
to the code :
var temp = document.getElementById("newValue").value;
choice.value = this.value * temp;
So, I'm going to recreate some stuff here. From what I can tell, you want to select a food item and output its weight in the other text field.
/* begin and done are input and output. */
var input=document.getElementById("input");
var output=document.getElementById("output");
/* Handles a change in the input text field, like if the user types apple, blueberry, etc. */
/* You could make this a keyup listener as well, I suppose. */
input.addEventListener("change",function(event_){
switch(this.value){
case "apple":
output.value="weight of apple";
break;
case "blueberry":
output.value="weight of blueberry";
break;
/* Optional default value for when the user is messing around. */
default:
output.value="Please select an item from the drop down list."
break;
}
});
Be sure to use conditionals to evaluate your output. I used a switch statement, but if statements are great, too! What I mean is this:
var x=10;
x=15;
x=7;
alert(x);// Returns 7
var y=Math.random()*100;
if (y<50){
alert("y is less than 50");
} else {
alert("y is greater than 50");
}
Multiple assignments in a row will be overwritten by subsequent assignments.
try this, I tested which can be work.
<body>
<form action="#">
<input type="text" id="begin" /> Apple
=
<input type="text" id="done" />
<select id="newValue" onchange = "f();">
<option value="1">Apple</option>
<option value="2">Blueberry</option>
<option value="3">Cheese</option>
</select>
<p id = "weight"></p>
</form>
<script>
var weightTag = document.getElementById('begin');
var totalTag = document.getElementById('done');
function f(){
var priceTag = document.getElementById('newValue');
if (weightTag.value != "") {
var index = priceTag.selectedIndex;
var priceValue = priceTag.options[index].value;
totalTag.value = weightTag.value * priceValue;
}
}
weightTag.onkeyup = f;
I think this is what you need.
<html>
<head>
</head>
<body>
<form action="#">
<input type="text" id="begin" onkeyup="k(1);" />
<select id="Fruitbox1" onclick="k(1);">
<option value = "3">Apple</option>
<option value = "1.5">Blueberry</option>
<option value = "1">Cherry</option>
</select>
=
<input type="text" id="done" onkeyup="k(0);"/>
<select id="Fruitbox2" onclick="k(0);">
<option
value="3">Apple</option>
<option value="1.5">Blueberry</option>
<option value="1">Cherry</option>
</select>
<p id = "leftWeight"></p>
<p id = "rightWeight"></p>
</form>
<script>
function k(x){
var weightOfFruit1=document.getElementById("Fruitbox1")
var weightOfFruit2=document.getElementById("Fruitbox2")
var NumberofFruit1=document.getElementById("begin")
var NumberofFruit2=document.getElementById("done")
if(x==1)
{
TotalNumberofFruit2=(NumberofFruit1.value * weightOfFruit1.value)/weightOfFruit2.value
NumberofFruit2.value=parseInt(TotalNumberofFruit2)
}else
{
TotalNumberofFruit1=(NumberofFruit2.value * weightOfFruit2.value)/weightOfFruit1.value
NumberofFruit1.value=parseInt(TotalNumberofFruit1)
}
}
</script>
</body>
</html>

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

Categories

Resources