Using HTML5 local storage - javascript

I am developing a small site and having trouble to maintain the persistence of a cost value across the web pages.
I have tried using the Html5 storage but I can't get it to work.
Here is my Javascript:
function modifyPrice(cost) {
// body...
var total = document.getElementById('totalCost');
var accumulte = total.value;
var temp = cost + Number.isInteger(accumulte) + 15;
total.value = temp;
localStorage.setItem("priceTag",temp);
document.getElementById('pricetag').innerHTML = localStorage.getItem("priceTag");
}
And here's my sample html:
<span>
<span name="price" id="pricetag"></span> $
</span>
Could it be the way I am executing localStorage or is there a better way?

Number.isInteger(accumulte) returns a boolean result. So you have to change your code to something like
var calculate = document.getElementById('calculate');
calculate.addEventListener("click", function() {
var total = document.getElementById('totalCost'),
accumulte = +total.value, // casting int to string.
cost = 10,
temp = cost + (Number.isInteger(accumulte) ? parseInt(accumulte, 10) : 0) + 15;
alert("Value when accumulte is " + total.value + " = " + temp);
}, false);
<input type="text" value="07" id="totalCost" />
<input type="button" value="Calculate" id="calculate" />

Related

Javascript passing variable and elementId to an function

var ingaveA = {
stuks: ""
};
var ingaveB = {
prijs: ""
};
var uitgave = {
totaal: ""
};
update(ingaveA, "testa", ingaveB, "testb", uitgave, "testc");
function update(refA, argsA, refB, argsB, refC, argsC) {
refA.stuks = document.getElementById(argsA).value;
refB.prijs = document.getElementById(argsB).value;
refC.totaal = refA.stuks * refB.prijs;
document.getElementById(argsC).value = refC.totaal;
}
ingaveA = ingaveA.stuks;
ingaveB = ingaveB.prijs;
uitgave = uitgave.totaal;
alert("Stuks=" + ingaveA + " Prijs=" + ingaveB + " Totaal=" + uitgave);
<input id="testa" value="10">
<input id="testb" value="6">
<input id="testc" value="">
Is there an better way to do this? always 3 variable names and 3 elements.
Maybe using an array ?
thanks in advance
Instead of using document.getElementById() for every input, you can use document.querySelectorAll() and [id^=test] to select all 3 and put them in a NodeList (think of it as an array).
[id^=test] means every id that starts with test
You can also make one general object, and update it as needed like below.
var ingave = {
ingaveA: {
stuks: ""
},
ingaveB: {
prijs: ""
},
uitgave: {
totaal: ""
}
};
var inputs = document.querySelectorAll("[id^=test]");
update(ingave, inputs);
function update(ref, inputs) {
ref.ingaveA.stuks = inputs[0].value;
ref.ingaveB.prijs = inputs[1].value;
ref.uitgave.totaal = ref.ingaveA.stuks * ref.ingaveB.prijs;
inputs[2].value = ref.uitgave.totaal;
}
var ingaveA = ingave.ingaveA.stuks;
var ingaveB = ingave.ingaveB.prijs;
var uitgave = ingave.uitgave.totaal;
alert("Stuks=" + ingaveA + " Prijs=" + ingaveB + " Totaal=" + uitgave);
<input id="testa" value="10">
<input id="testb" value="6">
<input id="testc" value="">
I'm not really sure what the question is here, but you don't need to create 3 separate objects.
let ingaveA = ""
let ingaveB = ""
let uitgave = ""
then just pass these 3 to your function:
function update(refA, refB, refC) {
refA = document.getElementById("testa").value;
refB = document.getElementById("testb").value;
refC = refA * refB;
document.getElementById("testc").value = refC.totaal;
}
Again, it's hard to optimize it as we don't know your specifics of the code.

Javascript input returns NaN or undefiend

I'm making a tip calculator and I would like the tip amount to display for the user to see. The problem I'm having is the output showing up as 'NaN' or 'undefined'. I've tried making changes to my code but I keep getting the same result.
function calculateTip() {
var billInput = document.getElementById('bill');
var tipPercentage = document.getElementById('tip');
var tipPercentageCalc = (tipPercentage / 100);
var tipAmount = (bill * tipPercentageCalc).toFixed(2);
tipAmount = tipAmount.toString();
document.getElementById('display_text').innerHTML = 'Tip = $', +tipAmount;
};
<div id='calculate'>
<p>Bill: $<input id="bill" type="number" name="bill" placeholder="Enter bill amount" onchange="calculateTip()"></p>
<p>Tip: %<input id="tip" type="number" name="tip" placeholder="15%" onchange="calculateTip()"></p>
<input type="button" name="submit" onclick="calculateTip();">
</div>
<div id="display">
<h4 id="display_text"></h4>
</div>
You forgot to get the value of your fields. Because without the property .value, it returns HTMLObject.
function calculateTip() {
var billInput = parseFloat(document.getElementById('bill').value);
var tipPercentage = parseFloat(document.getElementById('tip').value);
var tipPercentageCalc = (tipPercentage / 100);
var tipAmount = (bill * tipPercentageCalc).toFixed(2);
tipAmount = tipAmount.toString();
document.getElementById('display_text').innerHTML = 'Tip = $', + tipAmount;
};
You are reading billInput and tipPercentage as HTML element objects instead of the text the user types into them, which will be their .value properties.
function calculateTip() {
// get the VALUE property of the textbox elements
// parseInt will turn them into numbers if they're not already.
// if they are not numbers you cannot use them in math.
var billInput = parseInt(document.getElementById('bill').value);
var tipPercentage = parseInt(document.getElementById('tip').value);
var tipPercentageCalc = (tipPercentage / 100);
var tipAmount = (billInput * tipPercentageCalc);
// isNaN stands for "is Not a Number"
// this checks if tipAmount is not a number
// if it is not we simply set it to the number 0
if (isNaN(tipAmount)) {
tipAmount = 0;
}
// when you concatenate a number to a string you do not need to turn it into a string.
// it will automatically be converted
document.getElementById('display_text').innerHTML = 'Tip = $' + tipAmount;
};
function calculateTip() {
// get the VALUE property of the textbox elements
// parseInt will turn them into numbers if they're not already.
// if they are not numbers you cannot use them in math.
var billInput = parseInt(document.getElementById('bill').value);
var tipPercentage = parseInt(document.getElementById('tip').value);
var tipPercentageCalc = (tipPercentage / 100);
var tipAmount = (billInput * tipPercentageCalc);
// isNaN stands for "is Not a Number"
// this checks if tipAmount is not a number
// if it is not we simply set it to the number 0
if (isNaN(tipAmount)) {
tipAmount = 0;
}
// when you concatenate a number to a string you do not need to turn it into a string.
// it will automatically be converted
document.getElementById('display_text').innerHTML = 'Tip = $' + tipAmount;
};
<div id='calculate'>
<p>Bill: $<input id="bill" type="number" name="bill" placeholder="Enter bill amount" onchange="calculateTip()"></p>
<p>Tip: %<input id="tip" type="number" name="tip" placeholder="15%" onchange="calculateTip()"></p>
<input type="button" name="submit" onclick="calculateTip();">
</div>
<div id="display">
<h4 id="display_text"></h4>
</div>
You're loading the element instead of the element value when declaring the variables billInput and tipPercentage. Try with this code:
var billInput = document.getElementById('bill').value;
var tipPercentage = document.getElementById('tip').value;

Javascript won't calculate

Can anyone point me in the right direction as to why my calculate button will not calculate. It doesn't even throw any of the error messages up to the screen, but my clear button does work. It's probably something small, but I cannot figure it out for the life of me -_-.
var $ = function(id) {
return document.getElementById(id);
}
var virusRemovalPrice = 20.00;
var websiteMakingCost = 75.00;
var computerServicingCost = 100.00;
var calculateTotal = function() {
var virusRemoval = parseFloat($("virusRemoval").value);
var websiteMaking = parseFloat($("websiteMaking").value);
var computerOptimizationAndSetUp = parseFloat($("computerOptimizationAndSetUp").value);
var totalCost = parseFloat(($("totalCost").value));
if (isNaN(virusRemoval) || virusRemoval < 0) {
alert("Value must be numeric and at least zero. ");
$("virusRemoval").focus()
} else if (isNaN(websiteMaking) || websiteMaking < 0) {
alert("Value must be numeric and at least zero. ");
$("websiteMaking").focus()
} else if (isNaN(computerOptimizationAndSetUp) || computerOptimizationAndSetUp < 0) {
alert("Value must be numeric and at least zero. ");
$("computerOptimizationAndSetUp").focus()
} else {
do {
var ii = 0;
var cost = ((virusRemovalPrice * virusRemoval) + (websiteMakingCost * websiteMaking) + (computerServicingCost * computerOptimizationAndSetUp));
$("cost").value = cost.toFixed(2); //total cost final
if (cost > 1) {
alert("Your total is " + cost + " hope to see you soon!");
}
} while (ii = 0)
}
};
var clearValues = function() {
var virusRemoval = parseFloat($("virusRemoval").value = "");
var websiteMaking = parseFloat($("websiteMaking").value = "");
var computerOptimizationAndSetUp = parseFloat($("computerOptimizationAndSetUp").value = "");
var totalCost = parseFloat($("totalCost").value = "");
}
<form class="anotheremoved">
<h2>Total Cost</h2>
<label for="virusRemoval">Virus Removal:</label>
<br />
<input type="text" id="virusRemoval">
<br />
<label for="websiteMaking">Website Design:</label>
<br />
<input type="text" id="websiteMaking">
<br />
<label for="computerOptimizationAndSetUp">Computer Setup:</label>
<br />
<input type="text" id="computerOptimizationAndSetUp">
<br />
<br />
<label for="totalCost">Your Total Cost is:</label>
<input type="text" id="TotalCost" disabled>
<br />
<input class="removed" type="button" id="calculateTotal" value="Calculate " onblur="calculateTotal()">
<input class="removed" type="button" id="clear" value="Clear" onclick="clearValues()">
</form>
The reason why the loop is in there is because we were required to have a loop and I couldn't find a good reason to have one, so I used one that would always be true to get it out of the way lol. Probably will throw an infinate loop at me or something, but I'll figure that out later, I'm just trying to get the dang on thing to do something here haha. I've tried to rewrite this 2 other times and still get to the same spot, so I realize it's probably something small, and I am new to Javascript. Thank you.
The problem is that you have id="calculateTotal" in the input button. Element IDs are automatically turned into top-level variables, so this is replacing the function named calculateTotal. Simply give the function a different name from the button's ID.
You also have a typo. The ID of the Total Cost field is TotalCost, but the code uses $('totalCost') and $('cost').
It's also better to do the calculation in onclick, not onblur. Otherwise you have to click on the button and then click on something else to see the result.
In the clearValues function, there's no need to assign variables and call parseFloat. Just set each of the values to the empty string. You could also just use <input type="reset">, that resets all the inputs in the form to their initial values automatically.
var $ = function(id) {
return document.getElementById(id);
}
var virusRemovalPrice = 20.00;
var websiteMakingCost = 75.00;
var computerServicingCost = 100.00;
var calculateTotal = function() {
var virusRemoval = parseFloat($("virusRemoval").value);
var websiteMaking = parseFloat($("websiteMaking").value);
var computerOptimizationAndSetUp = parseFloat($("computerOptimizationAndSetUp").value);
var totalCost = parseFloat(($("TotalCost").value));
if (isNaN(virusRemoval) || virusRemoval < 0) {
alert("Value must be numeric and at least zero. ");
$("virusRemoval").focus()
} else if (isNaN(websiteMaking) || websiteMaking < 0) {
alert("Value must be numeric and at least zero. ");
$("websiteMaking").focus()
} else if (isNaN(computerOptimizationAndSetUp) || computerOptimizationAndSetUp < 0) {
alert("Value must be numeric and at least zero. ");
$("computerOptimizationAndSetUp").focus()
} else {
do {
var ii = 0;
var cost = ((virusRemovalPrice * virusRemoval) + (websiteMakingCost * websiteMaking) + (computerServicingCost * computerOptimizationAndSetUp));
$("TotalCost").value = cost.toFixed(2); //total cost final
if (cost > 1) {
alert("Your total is " + cost + " hope to see you soon!");
}
} while (ii = 0)
}
};
var clearValues = function() {
$("virusRemoval").value = "";
$("websiteMaking").value = "";
$("computerOptimizationAndSetUp").value = "";
$("TotalCost").value = "";
}
<form class="anotheremoved">
<h2>Total Cost</h2>
<label for="virusRemoval">Virus Removal:</label>
<br />
<input type="text" id="virusRemoval">
<br />
<label for="websiteMaking">Website Design:</label>
<br />
<input type="text" id="websiteMaking">
<br />
<label for="computerOptimizationAndSetUp">Computer Setup:</label>
<br />
<input type="text" id="computerOptimizationAndSetUp">
<br />
<br />
<label for="totalCost">Your Total Cost is:</label>
<input type="text" id="TotalCost" disabled>
<br />
<input class="removed" type="button" id="calculateTotalButton" value="Calculate " onclick="calculateTotal()">
<input class="removed" type="button" id="clear" value="Clear" onclick="clearValues()">
</form>

adding a result of a calculation to a span with javascript after a button is clicked

Hi I'm new to javascript and I would like you to help me figure out why I can't get the result of the random number generator to appear in the span tag after the user clicks a calculate button using the min and max number they entered. I believe there is nothing wrong with the random number function it's just when I want to use the random number function as an event handler for the onclick event for the button it doesn't work. well, what I did was, I made a function called answer to gather the users input and to use that input as a parameter for the the random number function that is being called inside the answer function.
Then I used the answer function as an event handler for the onclick thinking that it would have the result of the the random number generator and would apply that to the onclick. and I stored that in var called storage so I could place the result of the event in the span tag later.
Here is the js fiddle of the code. can you help me solve my problem by getting the result of the random_number function in to the span $("output") after the button $("calculate") click?
only pure javascript, no jquery please.
Thank you in advance for your help. and I'm sorry if I got terminology wrong and for bad spelling. http://jsfiddle.net/jack2ky/WDyMd/
<label for="min">Enter the min:</label>
<input type="text" id = "min" /> <br />
<label for="max">Enter the max:</label>
<input type="text" id = "max" /> <br />
<input type="button" id = "calculate" value = "calculate"/>
<span id ="output"> </span>
<script>
var $ = function(id){
return document.getElementById(id);
}
window.onload = function () {
var random_number = function(min, max, digits){
digits = isNaN(digits) ? 0 : parseInt(digits);
if(digits < 0){
digits = 0;
}else if (digits > 16){
digits = 16
}
if(digits == 0){
return Math.floor(Math.random() * (max - min +1)) +min;
}else {
var rand = Math.random() * (max - min) + min;
return parseFloat(rand.toFixed(digits));
}
}
var storage = $("calculate").onclick = answer;
var answer = function(){
var miny = $("min").value;
var maxy = $("max").value;
return random_number(miny, maxy);
}
$("output").firstChild.nodeValue = storage;
}
</script>
</body>
</html>
var storage = $("calculate").onclick = answer;
...
$("output").firstChild.nodeValue = storage;
These two statements are called on page load. What is happening is you are changing the value of variable storage but the statement var storage = $("calculate").onclick = answer;
is being called only once when the page loads. You need to update the answer when user clicks the button. So you can remove $("output").firstChild.nodeValue = storage; and update the answer function like:
var answer = function(){
var miny = parseInt( $("min").value );
var maxy = parseInt( $("max").value );
var ans = random_number(miny, maxy);
$("output").innerHTML = ans;
}
This should do it:
<!DOCTYPE html>
<html>
<head>
<script>
var $ = function(id){
return document.getElementById(id);
}
window.onload = function () {
var random_number = function(min, max, digits){
digits = isNaN(digits) ? 0 : parseInt(digits);
if(digits < 0){
digits = 0;
}else if (digits > 16){
digits = 16
}
if(digits == 0){
return Math.floor(Math.random() * (max - min +1)) +min;
}else {
var rand = Math.random() * (max - min) + min;
return parseFloat(rand.toFixed(digits));
}
}
$("calculate").onclick = function() {
var miny = $("min").value;
var maxy = $("max").value;
$("output").firstChild.nodeValue = random_number(miny, maxy);
}
}
</script>
</head>
<body>
<label for="min">Enter the min:</label>
<input type="text" id = "min" /> <br />
<label for="max">Enter the max:</label>
<input type="text" id = "max" /> <br />
<input type="button" id = "calculate" value = "calculate"/>
<span id ="output"> </span>
</body>
</html>
$("output").firstChild.nodeValue = storage;
This line seems to be the problem because your output-Element has no firstChild. So the value gets written nowhere.
Just use
> $("output").nodeValue = storage;
edit: Tested this in jsFiddle - this is not the solutions as mentioned below!
If You are able to get your value in the variable storage
then you can simply render this value in span as HTML
$("#output span").html = storage;

How do I call a function that enters text into a read-only text-box by clicking an HTML button?

I am trying to write a short piece of html code that, given two initial amounts, attempts to find the number greater than or equal to the first that wholly divides the second given amount. The code tries to divide the numbers, and if it is unsuccessful, adds 1 to the first number and tries to divide again, etc...
I want the code to return the value that does wholly divide the second number AND the answer to the division (with some plain text appearing around it).
Added to this, or at least I'd like there to be, is that upon clicking one of 5 different buttons a multiplication operation is performed on the first given number, it is rounded up to the nearest whole number, and THEN the function attempts to divide this into the second given number.
It's difficult to explain exactly what I want without showing you the code I have so far, so here it is:
<html>
<head>
<b>Rounded Commodity Pricing:</b><br>
</head>
<script language="Javascript">
var currency;
function setCurrency(val) {
var currency = val;
}
function finddivid(marketprice,tradevalue) {
var KWDex = 0.281955
var GBPex = 0.625907
var USDex = 1
var CADex = 0.998727
var EURex = 0.784594
if
(currency == "KWD")
var currencyMarketprice = Math.ceil(marketprice*KWDex);
else if
(currency == "GBP")
var currencyMarketprice = Math.ceil(marketprice*GBPex);
else if
(currency == "USD")
var currencyMarketprice = Math.ceil(marketprice*USDex);
else if
(currency == "CAD")
var currencyMarketprice = Math.ceil(marketprice*CADex);
else if
(currency == "EUR")
var currencyMarketprice = Math.ceil(marketprice*EURex);
if (tradevalue % currencyMarketprice == 0)
return ("tonnage = " + tradevalue / currencyMarketprice + " mt, and price = " + currencyMarketprice +" " +currency +" per mt");
else
{for (var counter = currencyMarketprice+1; counter<(currencyMarketprice*2); counter++) {
if (tradevalue % counter == 0)
return ("tonnage = " + tradevalue / counter + " mt, and price = " + counter +" " +currency +" per mt");}}
}
</script>
</head>
<p>Select currency:
<input type="button" value="KWD" OnClick="setCurrency('KWD')">
<input type="button" value="USD" OnClick="setCurrency('USD')">
<input type="button" value="GBP" OnClick="setCurrency('GBP')">
<input type="button" value="EUR" OnClick="setCurrency('EUR')">
<input type="button" value="CAD" OnClick="setCurrency('CAD')">
<P>Enter today's price of commodity in USD: <input name="mktprc" input type="number"><br><p>
<P>Enter value of trade: <input name="trdval" input type="number">
<input type="button" value="Calculate" OnClick="document.getElementById('showMeArea').value=finddivid(document.getElementById('mktprc'),document.getElementById('trdval')));">
<p>
<br><br>
<input name="showMeArea" readonly="true" size="100">
</html>
If you run this html in your browser you should see what I am trying to achieve.
I've tried for a while to get this to work and I don't know if the error if in the function or it the way I am trying to get the 'return' of the function 'finddivid' into the text box 'showMeArea'...
Here are the main problems/features that I need help with:
I would like to be able to click on one of the 'currency' buttons so that upon clicking, the variable 'currency' is assigned and then used in the function finddivid.
(2. This isn't as important right now, but eventually, once this is working, I'd like it so that upon clicking one of the currency buttons, it changes colour, or is highlighted or something so that the user knows which currency rate they are using.)
Upon entering the numbers into the two boxes I would like to click 'Calculate' and have it return what I've written in the function into the 'showMeArea' read-only box at the end of the code.
I know I'm probably missing loads of stuff and I might be miles away from success but I am very new to programming (started just a few days ago!) so would like any kind of help that can be offered.
Thanks in advance of your comments.
There are quite a few things wrong with your markup and javascript. You have unclosed paragraph tags, you set the scope of currency to be global but then define a local variable with the same name when you want to set it (which is why currency is never being set globally), you're using an if/else statement where a switch/case is more appropriate... there's probably a lot more, and the more you learn the more you'll discover. Having said all that, because it bothered me, here's a modified version of your code which seems to do what you were after :
<html>
<head>
<title>Rounded Commodity Pricing</title>
<script type="text/javascript">
var currency;
function setCurrency(val) {
currency = val;
}
function finddivid(marketprice, tradevalue) {
var KWDex = 0.281955
var GBPex = 0.625907
var USDex = 1
var CADex = 0.998727
var EURex = 0.784594
var currencyMarketprice;
switch (currency) {
case "KWD":
currencyMarketprice = Math.ceil(marketprice * KWDex);
break;
case "GBP":
currencyMarketprice = Math.ceil(marketprice * GBPex);
break;
case "USD":
currencyMarketprice = Math.ceil(marketprice * USDex);
break;
case "CAD":
currencyMarketprice = Math.ceil(marketprice * CADex);
break;
case "EUR":
currencyMarketprice = Math.ceil(marketprice * EURex);
break;
}
if (tradevalue % currencyMarketprice == 0)
return ("tonnage = " + tradevalue / currencyMarketprice + " mt, and price = " + currencyMarketprice + " " + currency + " per mt");
else {
for (var counter = currencyMarketprice + 1; counter < (currencyMarketprice * 2); counter++) {
if (tradevalue % counter == 0)
return ("tonnage = " + tradevalue / counter + " mt, and price = " + counter + " " + currency + " per mt");
}
}
}
function calculate() {
var mktprc = document.getElementById('mktprc');
var trdval = document.getElementById('trdval');
document.getElementById('showMeArea').value = finddivid(mktprc.value, trdval.value);
}
</script>
</head>
<p>
Select currency:
<input type="button" value="KWD" onclick="setCurrency('KWD')">
<input type="button" value="USD" onclick="setCurrency('USD')">
<input type="button" value="GBP" onclick="setCurrency('GBP')">
<input type="button" value="EUR" onclick="setCurrency('EUR')">
<input type="button" value="CAD" onclick="setCurrency('CAD')">
</p>
<p>Enter today's price of commodity in USD: <input id="mktprc" input type="number"><p>
<p>Enter value of trade: <input id="trdval" input type="number"></p>
<p><input type="button" value="Calculate" OnClick="calculate();"></p>
<p>
<input id="showMeArea" readonly="true" size="100">
</p>
</html>

Categories

Resources