JSFiddle - React, Tailwind, and code Playground
by shaneburgess
HTML
<section>
<h1>Change Calculator</h1>
<label>Enter amount of change due (0-99):</label>
<input type="text" id="cents" value="99"/>
<input type="button" value="Make Change" name="calculate" id="calculate" /><br><br>
<label>Quarters:</label>
<input type="text" id="quarters"><br>
<label>Dimes:</label>
<input type="text" id="dimes"><br>
<label>Nickels:</label>
<input type="text" id="nickels"><br>
<label>Pennies:</label>
<input type="text" id="pennies"><br>
</section>
CSS
/* type selectors */
article, aside, figure, footer, header, nav, section {
display: block;
}
body {
font-family: Arial, Helvetica, sans-serif;
background-color: white;
margin: 0 auto;
width: 650px;
border: 3px solid blue;
}
h1 {
color: blue;
margin-top: 0;
}
section {
padding: 1em 2em;
}
label {
float: left;
width: 16em;
text-align: right;
}
input {
margin-left: 1em;
margin-bottom: .5em;
}
JavaScript
/*
Shane Burgess
*/
var $ = function (id) {
return document.getElementById(id);
}
var make_change = function() {
//Grab the value of the input
var cents = $("cents").value;
//Create a json object that has the name and value and will keep track of number of them in change
var coins = {
quarters: { value: 25, numberOf: 0},
dimes: {value: 10, numberOf: 0},
nickels: { value: 5, numberOf: 0},
pennies: { value: 1, numberOf: 0}
};
//Loop the the coins
for (var key in coins) {
//Set the value
var val = coins[key].value;
/*
Loop and add coins to numberof as long as the value is less than the cents
then decrement the cents by the value of the coin
*/
while(val <= cents){
cents = cents - val;
coins[key].numberOf++;
}
//Set the input associated with the coin
$(key).value = coins[key].numberOf;
//Disable the input
$(key).disabled = true;
}
}
window.onload = function () {
$("calculate").onclick = make_change;
}