How to create BTC to USD calculator with vice versa conversion? - javascript

In the attached code, I have BTC to USD conversions working correctly, However, I am struggling to introduce a bilateral conversion from USD to BTC.
How can I have these two conversions working in parallel?
Thank you in advance for your efforts.
$("input[name='calc']").keyup(function(){
$.getJSON( "https://api.coindesk.com/v1/bpi/currentprice/usd.json",
function( data) {
var amountInBtc = parseFloat($("input[name='calc']").val());
//convert btc to usd
var exchangeRate = parseInt(data.bpi.USD.rate_float);
var amount = amountInBtc * exchangeRate;
$("input[name='rslt']").val(amount);
});
});
.calculator{
display:flex;
margin-top: 50px;
justify-content: center;
}
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
-webkit-appearance: none;
margin: 0;
}
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<!--------- Calculator----------------->
<div class="calculator">
<input type="number" name="calc" placeholder="BTC">
<div class="arrow" style="margin: 0 10px";>=</div>
<input type="number" name="rslt" placeholder="USD">
</div>

See below... simple approach is to use a class for both fields and call the onChange function on the class, and use variables for the field names instead of hard coding them inside your function. Also note that using toFixed(2) fixes 2 decimal points, which will be 0.00 for anything less than 0.01.
Everything else is self explanatory
$(".currencyField").keyup(function(){ //input[name='calc']
let convFrom;
if($(this).prop("name") == "btc") {
convFrom = "btc";
convTo = "usd";
}
else {
convFrom = "usd";
convTo = "btc";
}
$.getJSON( "https://api.coindesk.com/v1/bpi/currentprice/usd.json",
function( data) {
var origAmount = parseFloat($("input[name='" + convFrom + "']").val());
var exchangeRate = parseInt(data.bpi.USD.rate_float);
let amount;
if(convFrom == "btc")
amount = parseFloat(origAmount * exchangeRate);
else
amount = parseFloat(origAmount/ exchangeRate);
$("input[name='" + convTo + "']").val(amount.toFixed(2));
});
});
.calculator{
display:flex;
margin-top: 50px;
justify-content: center;
}
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
-webkit-appearance: none;
margin: 0;
}
<script src="https://code.jquery.com/jquery-3.5.1.min.js"></script>
<!--------- Calculator----------------->
<div class="calculator">
<input type="number" name="btc" class="currencyField" placeholder="BTC">
<div class="arrow" style="margin: 0 10px";>=</div>
<input type="number" name="usd" class="currencyField" placeholder="USD">
</div>

Related

Calculating values

Am having a problem in my jquery script to do multiplication
in my script this is the area of problem i have
<script>
$(document).ready(function(){
$(".parameter").on("input",function() {
var num = $('input[name="num"]').val();
var left = $('input[name="left"]').val();
var total = num * left %; // 2 x 50000 % = 1000
var finalr = left - total; // 50000 - 1000 = 49000
$(".result").text(finalr +" final result"); // prints 49000
});
})
</script>
I want to make calculation and results go to disabled input box automatically as i descried it in html comments
<!DOCTYPE html>
<html>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script>
<style>
#div1, #div2 {
position: relative;
display: block;
width: fit-content;
width: -moz-fit-content;
--val: '';
}
#div1::after {
content: var(--val) ' INX';
position: absolute;
left: 3px;
top: 1px;
bottom: 1px;
pointer-events: none;
line-height: 20px;
}
#left, #right {
font-family: inherit;
font-size: inherit;
}
#left {
color: transparent;
}
</style>
<body>
<p>
<input type="text" name="num" class="parameter" placeholder="amo"/> <! --- value set to 2 --->
</p>
<div id="div1">
<input type="text" id="left" name="left" class="parameter" maxlength="18" /></div> <! --- value set to 50000 --->
<div id="div2">
<input type="text" id="right" name="right" class="result" placeholder="INX" disabled /></div> <! --- 49000 results goes here --->
<script>
document.querySelector('#left').addEventListener('input', function() {
this.parentElement.style.setProperty('--val', "'"+this.value+"'");
document.querySelector('#right').value = this.value ? this.value + ' INX' : '';
});
</script>
<script>
$(document).ready(function(){
$(".parameter").on("input",function() {
var num = $('input[name="num"]').val();
var left = $('input[name="left"]').val();
var total = num * left %; // 2 x 50000 % = 1000
var finalr = left - total; // 50000 - 1000 = 49000
$(".result").text(finalr +" final result"); // prints 49000
});
})
</script>
</body>
</html>
the issue is you're trying to use % as a percentage. % is the Remainder operator.
what you can do is to replace
var total = num * left %;
with
var total = num * left/100;
try using
$(".result").val(finalr +" final result");
I haven't checked but I hope it works.

How to clear out form input in real-time if input value condition is met?

I have three input fields: nightly rate, weekly rate, and monthly rate. People on the site are getting confused on determining a weekly and monthly rate based on their nightly rate (not joking). I put a div next to the labels to show the nightly average for the week and/or month. You can see two ways I currently have the code. Each night has to be a minimum of $100, so I made a condition to only show the average nightly rate for the week if the condition of $700 is met. The problem is if you delete the values in the input the numbers still stay for the weekly rate. The numbers should disappear in real-time when deleted.
I also set the monthly amount to simply reflect in real-time what the user types.
If I decide to keep the condition for $700 how can I clear the values in real time like the monthly rate code currently does?
Please note: I realize I need to account somehow to not show if NaN, 0, etc. In the real app I will be using Ruby constants to calculate the week/month vs literal numbers like 7 or 30. Any help is appreciated.
const weeklyRateInput = document.getElementById('weekly-rate');
const monthlyRateInput = document.getElementById('monthly-rate');
const displayWeeklyRate = document.getElementById('weekly-avg-rate');
const displayMonthlyRate = document.getElementById('monthly-avg-rate');
weeklyRateInput.addEventListener('input', calcWeeklyRate);
function calcWeeklyRate() {
if (weeklyRateInput.value >= 700) {
displayWeeklyRate.innerHTML = '$' + Math.round(weeklyRateInput.value / 7) + ' per night';
}
return false;
}
monthlyRateInput.addEventListener('input', calcMonthlyRate);
function calcMonthlyRate() {
displayMonthlyRate.innerHTML = '$' + Math.round(monthlyRateInput.value / 30) + ' per night';
}
input,
label {
display: block;
}
label {
margin: 1%;
}
.container {
display: flex;
justify-content: flex-start;
align-items: center;
width: 500px;
}
#weekly-avg-rate {
float: right;
color: green;
}
#monthly-avg-rate {
float: right;
color: green;
}
<label for="nightly">Nightly Rate</label>
<input class="nightly-rate" id="nightly-rate" type="text" placeholder="$300">
<div class="container">
<label for="weekly">Weekly Rate</label>
<div id="weekly-avg-rate">
</div>
</div>
<input class="weekly-rate" id="weekly-rate" type="text" placeholder="$2000.">
<div class="container">
<label for="monthly">Monthly Rate</label>
<div id="monthly-avg-rate">
</div>
</div>
<input class="monthly-rate" id="monthly-rate" type="text" placeholder="$6000">
why don't you just simply check if input's value is '' and if it is hide the green text ?
function calcWeeklyRate() {
if (weeklyRateInput.value == '') {
displayWeeklyRate.innerHTML = '';
}
if (weeklyRateInput.value >= 700) {
displayWeeklyRate.innerHTML = '$' + Math.round(weeklyRateInput.value / 7) + ' per night';
}
return false;
}
const weeklyRateInput = document.getElementById('weekly-rate');
const monthlyRateInput = document.getElementById('monthly-rate');
const displayWeeklyRate = document.getElementById('weekly-avg-rate');
const displayMonthlyRate = document.getElementById('monthly-avg-rate');
weeklyRateInput.addEventListener('input', calcWeeklyRate);
function calcWeeklyRate() {
if (weeklyRateInput.value >= 700) {
displayWeeklyRate.innerHTML = '$' + Math.round(weeklyRateInput.value / 7) + ' per night';
} else {
displayWeeklyRate.innerHTML = '';
}
return false;
}
monthlyRateInput.addEventListener('input', calcMonthlyRate);
function calcMonthlyRate() {
if (monthlyRateInput.value == '' || monthlyRateInput.value < 30 || parseFloat(monthlyRateInput.value) != monthlyRateInput.value) {
displayMonthlyRate.innerHTML = '';
return;
}
displayMonthlyRate.innerHTML = '$' + Math.round(monthlyRateInput.value / 30) + ' per night';
}
input,
label {
display: block;
}
label {
margin: 1%;
}
.container {
display: flex;
justify-content: flex-start;
align-items: center;
width: 500px;
}
#weekly-avg-rate {
float: right;
color: green;
}
#monthly-avg-rate {
float: right;
color: green;
}
<label for="nightly">Nightly Rate</label>
<input class="nightly-rate" id="nightly-rate" type="text" placeholder="$300">
<div class="container">
<label for="weekly">Weekly Rate</label>
<div id="weekly-avg-rate">
</div>
</div>
<input class="weekly-rate" id="weekly-rate" type="text" placeholder="$2000.">
<div class="container">
<label for="monthly">Monthly Rate</label>
<div id="monthly-avg-rate">
</div>
</div>
<input class="monthly-rate" id="monthly-rate" type="text" placeholder="$6000">
The reason the text doesn't disappear is that when the value is less than 700 there is no code to tell it to do something.
Easiest thing to do would be to add an else statement which then clears the text.
function calcWeeklyRate() {
if (weeklyRateInput.value >= 700) {
displayWeeklyRate.innerHTML = '$' + Math.round(weeklyRateInput.value / 7) + ' per night';
}
else{
displayWeeklyRate.innerHTML = '';
}
}
Edit:
The reason the monthly one is "clearing" is because there is no condition like the weekly one so the code which updates it will always run
Here is an example that updated every field based on what is entered where
const nightlyRateInput = document.getElementById('nightly-rate');
const weeklyRateInput = document.getElementById('weekly-rate');
const monthlyRateInput = document.getElementById('monthly-rate');
const displayNightlyRate = document.getElementById('nightly-avg-rate');
const displayWeeklyRate = document.getElementById('weekly-avg-rate');
const displayMonthlyRate = document.getElementById('monthly-avg-rate');
document.getElementById("rateDiv").addEventListener('input', calcRate);
function calcRate(e) {
const tgt = e.target;
const rate = +e.target.placeholder.replace('$','')
displayWeeklyRate.innerHTML = ""
displayMonthlyRate.innerHTML = ""
displayNightlyRate.innerHTML = ""
let n = 0
let w = 0
let m = 0
if (tgt.value.trim() === "") return;
if (tgt.id === "monthly-rate") {
n = Math.round(rate / 30)
w = Math.round(rate / 4)
m = rate
nightlyRateInput.value = ""
weeklyRateInput.value = ""
}
else if (tgt.id === "weekly-rate") {
n = Math.round(rate / 4)
w = rate
m = Math.round(rate * 4)
nightlyRateInput.value = ""
monthlyRateInput.value = ""
}
else if (tgt.id === "nightly-rate") {
n = rate
w = Math.round(rate * 4)
m = Math.round(rate * 30)
weeklyRateInput.value = ""
monthlyRateInput.value = ""
}
displayWeeklyRate.innerHTML = '$' + w + ' per week';
displayMonthlyRate.innerHTML = '$' + m + ' per month';
displayNightlyRate.innerHTML = '$' + n + ' per night';
};
input,
label {
display: block;
}
label {
margin: 1%;
}
.container {
display: flex;
justify-content: flex-start;
align-items: center;
width: 500px;
}
#weekly-avg-rate {
float: right;
color: green;
}
#monthly-avg-rate {
float: right;
color: green;
}
<div id="rateDiv">
<div class="container">
<label for="nightly">Nightly Rate</label>
<div id="nightly-avg-rate"></div>
<input class="nightly-rate" id="nightly-rate" type="text" placeholder="$300" autocomplete="off" />
</div>
<div class="container">
<label for="weekly">Weekly Rate</label>
<div id="weekly-avg-rate"></div>
<input class="weekly-rate" id="weekly-rate" type="text" placeholder="$2000" autocomplete="off" />
</div>
<div class="container">
<label for="monthly">Monthly Rate</label>
<div id="monthly-avg-rate">
</div>
<input class="monthly-rate" id="monthly-rate" type="text" placeholder="$6000" autocomplete="off" />
</div>
</div>

For MM/DD/YYYY text, display only that text which is not entered by user

I have a page like below image
According to my requirement, user is allowed to enter digits from the keypad that is provided on the page only. So input field is readonly.
Now I am trying to get is, when user start entering month then other text should remain in text field until user types that. e.g. 05/DD/YYYY like this. And accordingly that text will be hide.
If I placed placeholder then when user starts entering digits all text gone. I don't want that. So I have taken "MM/DD/YYYY" text in seperate span tag.
var Memory = "0", // initialise memory variable
Current = "", // and value of Display ("current" value)
Operation = 0, // Records code for eg * / etc.
MAXLENGTH = 8; // maximum number of digits before decimal!
function format(input, format, sep) {
var output = "";
var idx = 0;
for (var i = 0; i < format.length && idx < input.length; i++) {
output += input.substr(idx, format[i]);
if (idx + format[i] < input.length) output += sep;
idx += format[i];
}
output += input.substr(idx);
return output;
}
function AddDigit(dig) { //ADD A DIGIT TO DISPLAY (keep as 'Current')
if (Current.indexOf("!") == -1) { //if not already an error
if ((eval(Current) == undefined) &&
(Current.indexOf(".") == -1)) {
Current = dig;
document.calc.display.focus();
} else {
Current = Current + dig;
document.calc.display.focus();
}
Current = Current.toLowerCase(); //FORCE LOWER CASE
} else {
Current = "Hint! Press 'Clear'"; //Help out, if error present.
}
if (Current.length > 0) {
Current = Current.replace(/\D/g, "");
Current = format(Current, [2, 2, 4], "/");
}
document.calc.display.value = Current.substring(0, 10);
document.getElementById("cursor").style.visibility = "hidden";
}
function Clear() { //CLEAR ENTRY
Current = "";
document.calc.display.value = Current;
document.calc.display.focus();
document.getElementById("cursor").style.visibility = "visible";
//setInterval ("cursorAnimation()", 5000);
}
function backspace() {
Current = document.calc.display.value;
var num = Current;
Current = num.slice(0,num.length - 1);
document.calc.display.value = Current;
document.calc.display.focus();
document.getElementById("cursor").style.visibility = "hidden";
}
function cursorAnimation() {
$("#cursor").animate({
opacity: 0
}, "fast", "swing").animate({
opacity: 1
}, "fast", "swing");
}
//--------------------------------------------------------------->
$(document).ready(function() {
document.getElementById("cursor").style.visibility = "visible";
//setInterval ("cursorAnimation()", 1000);
});
.intxt1 {
padding: 16px;
border-radius: 3px;
/* border: 0; */
width: 1017px;
border: 1px solid #000;
font-family: Droid Sans Mono;
background: #fff;
}
.txtplaceholder {
font-family: "Droid Sans Mono";
color: #D7D7D7;
position: relative;
float: left;
left: 219px;
top: 17px;
z-index: 10 !important;
overflow: hidden;
white-space: nowrap;
text-overflow: ellipsis;
display: inline-block;
}
#cursor {
position: relative;
z-index: 1;
left: 32px;
top: 2px;
visibility: hidden;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>
<form Name="calc" method="post">
<div style="position:relative">
<span id="cursor">_</span>
<span class="txtplaceholder">MM/DD/YYYY</span>
<span style="z-index:100">
<input class="intxt1" autocomplete="off" id="pt_dob" name="display" value="" type="text" readonly>
</span>
<button class="cancel-icon" type="reset" onClick="Clear()"></button>
</div>
<div class="num_keypad1" style=" margin-top:19px;">
<!-- Screen and clear key -->
<div class="num_keys">
<!-- operators and other keys -->
<span id="key1" onClick="AddDigit('1')">1</span>
<span id="key2" onClick="AddDigit('2')">2</span>
<span id="key3" onClick="AddDigit('3')">3</span>
<span id="key4" onClick="AddDigit('4')">4</span>
<span id="key5" onClick="AddDigit('5')">5</span>
<span id="key6" onClick="AddDigit('6')">6</span>
<span id="key7" onClick="AddDigit('7')">7</span>
<span id="key8" onClick="AddDigit('8')">8</span>
<span id="key9" onClick="AddDigit('9')">9</span>
<span id="key0" onClick="AddDigit('0')" style="width: 200px;">0</span>
<span id="keyback" class="clear" onClick="backspace()"> <div class="num_xBox">X</div></span>
</div>
</div>
</form>
With the above Html code I am getting below result:
Problems coming are below:
My digits are going below the text "MM/DD/YYYY". I am not getting how should I get my digits above that text
How should I hide the text which is entered by user and display other accordingly e.g. "MM" should hide if user enters 05 and display other text like this "05/DD/YYYY".
Can anyone please help me in this?
NOTE: With input type=date or by any other plugins I can achieve above functionality but my requirement is different. I have to achieve this with HTML, CSS, JS only.
I would use a ready built data picker for this kind of thing as it would have all the error checking in built to ensure you enter a date in the correct format.
The way you are doing it, you are not able to check if the day is valid until you have entered the month, by which time the user will have to backspace and it will be a very slow and clunky process which is not very user friendly.
Anyway, if you persist with a number pad, here is how I would do it.
put the date in a global array
have a global index counter
add and remove values based on the index counter
The following is a very quick example of the above
var dateBits = ["D", "D", "M", "M", "Y", "Y", "Y", "Y"],
letters = ["D", "D", "M", "M", "Y", "Y", "Y", "Y"],
input = document.getElementById('pt_dob'),
currentIndex = 0;
function makeDate() {
return dateBits[0] + dateBits[1] + "/" + dateBits[2] + dateBits[3] + "/" + dateBits[4] + dateBits[5] + dateBits[6] + dateBits[7];
}
function AddDigit(number) {
dateBits[currentIndex] = number;
if (currentIndex < 8) {
currentIndex++;
}
input.value = makeDate();
}
function RemoveDigit() {
if (currentIndex > 0) {
currentIndex--;
}
dateBits[currentIndex] = letters[currentIndex];
input.value = makeDate();
}
function Clear() {
for (i = 0; i < letters.length; i++) {
dateBits[i] = letters[i];
}
currentIndex = 0;
input.value = makeDate();
}
input.value = makeDate(); // run this line onload or include this whole script at the bottom of the page to get your input to start with your text
.intxt1 {
padding: 16px;
border-radius: 3px;
/* border: 0; */
width: 1017px;
border: 1px solid #000;
font-family: Droid Sans Mono;
background: #fff;
}
#cursor {
position: relative;
z-index: 1;
left: 32px;
top: 2px;
visibility: hidden;
}
.num_keys > span {
display: inline-flex;
width: 2em;
height: 2em;
align-items: center;
justify-content: center;
cursor: pointer;
border: 1px solid black;
}
<form Name="calc" method="post">
<div style="position:relative"><span id="cursor">_</span>
<span class="txtplaceholder">MM/DD/YYYY</span><span style="z-index:100"><input class="intxt1" autocomplete="off" id="pt_dob" name="display" value="" type="text" autocomplete="off" readonly></span>
<button class="cancel-icon" type="reset" onClick="Clear(); return false;">clear</button>
</div>
<div class="num_keypad1" style=" margin-top:19px;">
<!-- Screen and clear key -->
<div class="num_keys">
<!-- operators and other keys -->
<span id="key1" onClick="AddDigit('1')">1</span>
<span id="key2" onClick="AddDigit('2')">2</span>
<span id="key3" onClick="AddDigit('3')">3</span>
<span id="key4" onClick="AddDigit('4')">4</span>
<span id="key5" onClick="AddDigit('5')">5</span>
<span id="key6" onClick="AddDigit('6')">6</span>
<span id="key7" onClick="AddDigit('7')">7</span>
<span id="key8" onClick="AddDigit('8')">8</span>
<span id="key9" onClick="AddDigit('9')">9</span>
<span id="key0" onClick="AddDigit('0')" style="width: 200px;">0</span>
<span id="keyback" class="clear" onClick="RemoveDigit()"> <div class="num_xBox">X</div></span>
</div>
</div>
</form>
var text = "DD/MM/YYYY";
$(".textbox").on("focus blur", function(){
$(".wrapper").toggleClass("focused");
});
$(".wrapper").click(function (e) {
if (e.target == this) {
var b = $(".textbox", this).focus();
}
}).trigger("click");
$(".wrapper > .textbox").on("input", function(){
var ipt = $(this).text().replace(/\u00A0/g, " ");
$(".gray").text(text.substr(ipt.length, text.length));
}).trigger("input");
check this fiddle http://jsfiddle.net/7sD2r/22/
If ive understood all well. I think the one solution is to store user input in hidden field. Then get this input to split digits and return to visible input value that consists of splitted values etc.

Validating function written in javaScript runs only once?

goal : is to validate this form. http://jsbin.com/buwejurexa/1/
Code is below
Show the user all errors at once when he clicks Save Product button and errors at each step also.
What is done:
Wrote a validating function returnVal() which is nested inside another function called displayStorage.
What works :
As the page loads the user clicks the Save Product button and the validating function seems to be working first time. I can see the alert.
The issue starts when:
The user selects the Category and Products and sees Wattage. This
time he decides to click on Save Product. Nothing happens. No
Validations are displayed step by step.
No errors in Console but got a error in JS Bin that (Line 253: Expected a conditional expression and instead saw an assignment.
Line 258: Unreachable 'return' after 'return'.)
My guess :
a) my if and else statement is missing something. I tried calling it from different functions but no luck.
b) The four buttons use Jquery. so I am guessing do I need to call javascript function returnVal() inside Jquery. How do I do that. I did reference the 4 buttons in my validating function.
can some help me get the validations right.
Thanks!!
var wattage = {
'Artic King AEB': 100,
'Artic King ATMA': 200,
'Avanti Compact': 300,
'Bosch SS': 400,
'Bosch - SHXUC': 100,
'Asko DS': 200,
'Blomberg': 300,
'Amana': 400
};
var annualEnergy = 0;
var dailyEnergyConsumed = 0;
function populateProducts(category, products) {
var refrigerators = new Array('Artic King AEB', 'Artic King ATMA', 'Avanti Compact', 'Bosch SS');
var dishWasher = new Array('Bosch - SHXUC', 'Asko DS', 'Blomberg', 'Amana');
switch (category.value) {
case 'refrigerators':
products.options.length = 0;
for (i = 0; i < refrigerators.length; i++) {
createOption(products, refrigerators[i], refrigerators[i]);
}
break;
case 'dishWasher':
products.options.length = 0;
for (i = 0; i < dishWasher.length; i++) {
createOption(products, dishWasher[i], dishWasher[i]);
}
break;
default:
products.options.length = 0;
break;
}
populateWattage(products);
}
function createOption(ddl, text, value) {
var opt = document.createElement('option');
opt.value = value;
opt.text = text;
ddl.options.add(opt);
}
function populateWattage(product) {
document.getElementById('wattage').innerText = wattage[product.value];
populateStorage();
}
function setConsumption(hrs) {
setConsumption();
}
dailyEnergyConsumption = function(hrs) {
dailyEnergyConsumed = 0;
dailyEnergyConsumed = parseFloat(hrs * parseInt(document.getElementById('wattage').innerText) / 1000).toFixed(2);
document.getElementById('dailyEnergyConsumptionVal').innerText = dailyEnergyConsumed + " kWh";
populateStorage();
};
annualEnergyConsumption = function(days) {
annualEnergy = 0;
var allYear = document.getElementById('allYear');
var halfYear = document.getElementById('halfYear');
var threeMonths = document.getElementById('threeMonths');
var oneMonth = document.getElementById('oneMonth');
if (allYear || days != 365) {
annualEnergy = parseFloat(dailyEnergyConsumed * parseInt(days)).toFixed(2);
document.getElementById('annualEnergyConsumption').innerText = annualEnergy + " kWh";
} else if (days == 182 && !halfYear) {
annualEnergy = parseFloat(dailyEnergyConsumed * parseInt(days)).toFixed(2);
document.getElementById('annualEnergyConsumption').innerText = annualEnergy + " kWh";
} else if (days == 90 && !threeMonths) {
annualEnergy = parseFloat(dailyEnergyConsumed * parseInt(days)).toFixed(2);
document.getElementById('annualEnergyConsumption').innerText = annualEnergy + " kWh";
} else if (days == 30 && !oneMonth) {
annualEnergy = parseFloat(dailyEnergyConsumed * parseInt(days)).toFixed(2);
document.getElementById('annualEnergyConsumption').innerText = annualEnergy + " kWh";
}
populateStorage();
};
// code that shows which button is clicked. Green div below the 4 buttons
$(document).ready(function() {
$("#h1").click(function() {
$("#onesSelected").show();
$("#threeSelected").hide();
$("#sixSelected").hide();
$("#twentyFourSelected").hide();
});
$("#h3").click(function() {
$("#threeSelected").show();
$("#onesSelected").hide();
$("#sixSelected").hide();
$("#twentyFourSelected").hide();
});
$("#h6").click(function() {
$("#sixSelected").show();
$("#onesSelected").hide();
$("#threeSelected").hide();
$("#twentyFourSelected").hide();
});
$("#h24").click(function() {
$("#twentyFourSelected").show();
$("#onesSelected").hide();
$("#threeSelected").hide();
$("#sixSelected").hide();
});
});
function compareSetup() {
var prodName = localStorage.getItem('productKey');
var energyName = parseInt(localStorage.getItem('energyKey'), 10);
var useName = parseInt(localStorage.getItem('estimatedUse'), 10);
return false;
}
function populateStorage() {
var productBox = document.getElementById("products");
var productName = productBox.options[productBox.selectedIndex].text;
localStorage.setItem('productKey', productName);
localStorage.setItem('energyKey', document.getElementById("annualEnergyConsumption").innerHTML);
//localStorage.setItem.querySelector('input[id="usageRadio"]:checked').value;
//localStorage.setItem('usageRadio' + $(this).attr('id'), JSON.stringify({ checked: this.checked }));
//localStorage.setItem('estimatedUse', document.getElementById("usageRadio"));
// do other things if necessary
}
function displayStorage() {
var displayProduct = document.getElementById("displayName");
var displayAnnual = document.getElementById("displayAnnual");
displayProduct.innerHTML = "Selected Product: " + localStorage.getItem('productKey');
displayProduct.style = "display:inline;";
displayAnnual.innerHTML = "Annual Consumption: " + localStorage.getItem('energyKey');
returnVal();
}
//validation code starts here
function returnVal() {
//initialize the form elements starting from form name , category and product dropdown, daily use buttons and finally the radio buttons
var energyForm = document.getElementsByName("energyForm")[0];
// drop downs
var catDropdown = document.getElementById("dd1");
var prodDropdown = document.getElementById("products");
// call the 4 Daily use button
var notLotButton = document.getElementById("h1");
var averageButton = document.getElementById("h3");
var lotButton = document.getElementById("h6");
var alwaysButton = document.getElementById("h24");
// radio button group
var allYearRadio = document.getElementById("allYear");
var halfYearRadio = document.getElementById("halfYear");
var threeMonthsRadio = document.getElementById("threeMonths");
var oneMonthRadio = document.getElementById("oneMonth");
//
var missingFields = false;
var strFields = "";
if (catDropdown.selectedIndex === 0) {
missingFields = true;
strFields += "Select Category and the related Product \n";
catDropdown.focus();
} else {
return true;
}
if ((!notLotButton.clicked) &&
(!averageButton.clicked) &&
(!lotButton.clicked) &&
(!alwaysButton.clicked)) {
missingFields = true;
strFields += "Select atleast one Estimated Daily Use option \n";
} else {
return true;
}
if ((!allYearRadio.checked) &&
(!halfYearRadio.checked) &&
(!threeMonthsRadio.checked) &&
(!oneMonthRadio.checked)) {
missingFields = true;
strFields += "Select atleast one Estimated Yearly Use option \n";
} else {
return true;
}
if (missingFields = true) {
alert("Please provide the following fields before continuing: \n" + strFields);
}
return false;
return true;
}
function resetForm() {
document.getElementById("resetButton");
document.getElementById("energyForm").reset();
document.getElementById('products').value = "select";
//document.getElementById('select_value').selectedIndex = 3;
}
#leftColumn {
width: 600px;
float: left;
}
.placeholderText {
font: bold 12px/30px Georgia, serif;
}
body {
padding-left: 45px;
}
#annualEnergyConsumption {
font: bold 25px arial, sans-serif;
color: #00ff00;
}
#dailyEnergyConsumptionVal {
font: bold 25px arial, sans-serif;
color: #00ff00;
}
#annualCostOperation {
font: bold 40px arial, sans-serif;
color: #00ff00;
}
.dailyButInline {
display: inline;
}
#wattage {
position: absolute;
left: 160px;
top: 130px;
font: bold 25px arial, sans-serif;
color: #00ff00;
}
/* mouse over link */
button:hover {
background-color: #b6b6b6;
}
#onesSelected {
position: absolute;
left: 53px;
top: 246px;
background-color: #00ff00;
display: none;
width: 99px;
height: 5px;
}
#threeSelected {
position: absolute;
left: 156px;
top: 246px;
background-color: #00ff00;
display: none;
width: 99px;
height: 5px;
}
#sixSelected {
position: absolute;
left: 259px;
top: 246px;
background-color: #00ff00;
display: none;
width: 99px;
height: 5px;
}
#twentyFourSelected {
position: absolute;
left: 362px;
top: 246px;
background-color: #00ff00;
display: none;
width: 113px;
height: 5px;
}
#store {
cursor: pointer;
}
<h2>Annual Energy Consumption and Cost Calculator</h2>
<form id="energyForm" onSubmit="return compareSetup()" action="" method="post">
<div id="leftColumn">
<div>
<span class="placeholderText">Choose Category</span>
<span>
<select id="dd1" name="dd1" onchange="populateProducts(this,document.getElementById('products'))" required>
<option value="select">Select-a-Category</option>
<option value="refrigerators">Refrigerators</option>
<option value="dishWasher">DishWasher</option>
</select>
</span>
</br>
<span class="placeholderText">Select a Product</span>
<span>
<select id="products" onchange="populateWattage(this)" required>
<option value="select" selected>--------------------------</option>
</select>
</span>
</div>
<div>
<span class="placeholderText">Wattage</span>
<span id="wattage">0</span>
</br>
</br>
</div>
<div id="buttonBoundary">
<div class="placeholderText">Estimated Daily Use</div>
<div class="dailyButInline">
<button type="button" id="h1" onclick="dailyEnergyConsumption(1)">Not a Lot</br>1 hour per day</button>
</div>
<div class="dailyButInline">
<button type="button" id="h3" onclick="dailyEnergyConsumption(3)">Average</br>3 hour per day</button>
</div>
<div class="dailyButInline">
<button type="button" id="h6" onclick="dailyEnergyConsumption(6)">A Lot</br>6 hour per day</button>
</div>
<div class="dailyButInline">
<button type="button" id="h24" onclick="dailyEnergyConsumption(24)">Always On</br>24 hours per day</button>
</div>
<div id="onesSelected"></div>
<div id="threeSelected"></div>
<div id="sixSelected"></div>
<div id="twentyFourSelected"></div>
</br>
</br>
</div>
<div>
<span class="placeholderText">Daily Energy Consumption</span>
</br>
<div id="dailyEnergyConsumptionVal">---</div>
</br>
</div>
<div>
<span class="placeholderText">Estimated Yearly Use</span>
</br>
<input type="radio" name="usageRadio" value="365" id="allYear" onclick="annualEnergyConsumption(365)" />
<label for="allYear">All year</label>
<input type="radio" name="usageRadio" value="182" id="halfYear" onclick="annualEnergyConsumption(182)" />
<label for="halfYear">6 Months</label>
<input type="radio" name="usageRadio" value="90" id="threeMonths" onclick="annualEnergyConsumption(90)" />
<label for="threeMonths">3 Months</label>
<input type="radio" name="usageRadio" value="30" id="oneMonth" onclick="annualEnergyConsumption(30)" />
<label for="oneMonth">1 Month</label>
<!-- <div id="daysUsed"><input type="number" id="hour" maxlength="2" min="1" onchange="annualEnergyConsumption(this.value)"></br> -->
</div>
</br>
<div>
<span class="placeholderText">Energy Consumption</span>
</br>
<div id="annualEnergyConsumption">---</div>
</br>
</div>
<input type="submit" value="Save Product" onclick="displayStorage()" />
<input type="reset" onclick="resetForm()" id="resetButton" value="Reset" />
</div>
<div id="right">
<div id="displayName">Selected Product:</div>
<div id="displayAnnual">Annual Consumption:</div>
</div>
</form>
In the last statements of your function, there are two mistakes:
if (missingFields = true) { // should be: missingFields == true
alert("Please provide the following fields before continuing: \n" + strFields);
}
return false;
return true; // You already returned false; did you mean to return false inside the if?

Homework help - Javascript coin jar

Our teacher asked us to create a jar of coins that will count how many pennies, dimes, and etc we have and then gives a total amount of money.
this is the template that he want us to use
https://online.pcc.edu/content/enforced/70599-22278.201302/labs/frameworks/Lab4Template.html?_&d2lSessionVal=0Zb6SMZBBcQ8ENPN4HdQk4js0
He want us to enter pennies, nickels, dimes, quarters in the same text box separated by comma. My question is, How can I do that? I don't know how to do that in JavaScript. Can anyone lead me in the right direction.
here is the code
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<title> 122 Lab 4 Template </title>
<meta name="author" content="Lee Middleton" />
<meta name="keywords" content="CIS122" />
<meta name="description" content="CIS 122 Lab 4" />
<link rel="stylesheet" type="text/css" href="/content/enforced/70599-22278.201302/labs/frameworks/../../new122_Style.css?_&d2lSessionVal=FeMQRN1p4YNBW7SRb8H38sRQW" />
<style type="text/css">
.container {
border: 1px solid black;
border-radius: 15px;
width: 350px;
margin: 25px auto;
padding: 10px;
}
.result {
width: 175px;
float: left;
}
p { margin: 5px 0 0 5px;}
.clear { clear: both; }
input[type='button'] {
margin: 10px 0 0 5px;
}
</style>
<script language="javascript">
function countCoins()
{
// Add your code here to count the coins and display your answers
}
</script>
<script type="text/javascript" src="/d2l/common/mathjax/2.0/MathJax.js?config=MML_HTMLorMML%2c%2fd2l%2flp%2fmath%2fdisplay%2fconfig.js%3fv%3d9.4.1000.156-10" ></script></head>
<body>
<h1>CIS 122 Lab 4</h1>
<div class="container">
<h2>SORT-O-COIN</h2>
<form name="clubForm" style="margin-bottom: 10px;">
<div style="margin-left: 10px;">Coin Jar <input name="coinJar" size="40" type="text" /></div>
<p>Number of pennies: <span name="pennies"></span></p>
<p>Number of nickels: <span name="pennies"></span></p>
<p>Number of dimes: <span name="pennies"></span></p>
<p>Number of quarters: <span name="pennies"></span></p>
<p>Number of half-dollars: <span name="pennies"></span></p>
<p>Total number of coins: <span name="totalCoins"></span></p>
<p>Total value: <span name="totalValue"></span></p>
<input value="Count the coins" onclick="countCoins()" type="button" /></form></div>
</body>
</html>
Your text, split by comma using String.split
var valuesArray = yourInput.split(',');
It gives an array of values that were split by the ,. They are accessible by indexes.
var first = valuesArray[0];
var second = valuesArray[1]; //and so on...
As for counting, you can figure it out from there.
You can use this as a reference.
Note: this may not be complete, some bits may still need to be done, but it demonstrates all that you should need to know, to deal with such a question, or give you specific things to search/ask questions about so that you may learn.
CSS
.container {
border: 1px solid black;
border-radius: 15px;
width: 350px;
margin: 25px auto;
padding: 10px;
}
.result {
width: 175px;
float: left;
}
p {
margin: 5px 0 0 5px;
}
.clear {
clear: both;
}
input[type='button'] {
margin: 10px 0 0 5px;
}
HTML
<h1>CIS 122 Lab 4</h1>
<div class="container">
<h2>SORT-O-COIN</h2>
<form id="clubForm" style="margin-bottom: 10px;">
<div style="margin-left: 10px;">Coin Jar
<input id="coinJar" size="40" type="text">
</div>
<p>Number of pennies: <span id="pennies"></span>
</p>
<p>Number of nickels: <span id="nickels"></span>
</p>
<p>Number of dimes: <span id="dimes"></span>
</p>
<p>Number of quarters: <span id="quarters"></span>
</p>
<p>Number of half-dollars: <span id="halfDollars"></span>
</p>
<p>Total number of coins: <span id="totalCoins"></span>
</p>
<p>Total value: <span id="totalValue"></span>
</p>
<input value="Count the coins" id="countCoinsButton" type="button">
</form>
</div>
Javascript
(function (global) {
var types = "pennies nickels dimes quarters halfDollars".split(" "),
worths = "0.01 0.05 0.10 0.25 0.5".split(" "),
numTypes = types.length,
totals = {},
coinJar,
clubForm;
function countCoins() {
var values = coinJar.value.trim().split(","),
length = Math.min(numTypes, values.length),
i = 0,
coins,
value;
clubForm.reset();
while (i < length) {
value = values[i].trim();
if (value !== "") {
coins = parseInt(value, 10) || 0;
totals[types[i]] = (totals[types[i]] || 0) + coins;
totals["coins"] = (totals["coins"] || 0) + coins;
totals["value"] = parseFloat(((totals["value"] || 0) + (coins * parseFloat(worths[i]))).toFixed(2));
}
i += 1;
}
length = types.length;
i = 0;
while (i < length) {
document.getElementById(types[i]).textContent = totals[types[i]] || 0;
i += 1;
}
document.getElementById("totalCoins").textContent = totals["coins"] || 0;
document.getElementById("totalValue").textContent = totals["value"] || "0.00";
}
global.addEventListener("load", function onLoad() {
global.removeEventListener("load", onLoad);
clubForm = document.getElementById("clubForm");
coinJar = document.getElementById("coinJar");
document.getElementById("countCoinsButton").addEventListener("click", countCoins, false);
}, false);
}(window))
On jsfiddle
First you need to split the text of textbox.
var value = mystring.split(",");
Then go though each item of the array.
First you add value[x] to the total coin count.
Then set the id of the coin type to the value of value[x] for example
document.getElementById('pennies').innerHTML = value[0];
Then take value[x] times the coin value, for example
totalamount = totalamount + (value[x] * 1);
for pennies and add it to the total amount.
At the end you can set the total value with
document.getElementById('totalValue').innerHTML = totalamount.
Overall, it would be something like this:
function countCoins () {
// Add your code here to count the coins and display your answers
var coinJar = document.getElementsByName("coinJar")[0].value; //first get the value
var coinArray = coinJar.split(","); //split it
var values = [0.01, 0.05, 0.10, 0.25, 0.50]; //coin values
var ids = ['pennies', 'nickels', 'dimes', 'quarters', 'halfdollars']; //ids of coins*
var total = 0; //total dollar amount
var coinnumber = 0; //amount of coins.
for (var i = 0; i < coinArray.length; i++) {
var currentvalue = parseInt(coinArray[i]); //value of current coin
document.getElementsByName(ids[i])[0].innerHTML = currentvalue; //set the html
total += currentvalue * values[i];
coinnumber += currentvalue;
}
document.getElementsByName('totalValue')[0].innerHTML = total;
document.getElementsByName('totalCoins')[0].innerHTML = coinnumber;
}
JSFiddle

Categories

Resources