JSFiddle - React, Tailwind, and code Playground

by Graham Fairweather

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>

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;
}

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;

        clubForm.reset();
        while (i < length) {
            if (values[i] !== "") {
                coins = parseInt(values[i], 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))