1

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?_&amp;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>
razlebe
  • 7,134
  • 6
  • 42
  • 57
Augusto
  • 19
  • 3

3 Answers3

1

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.

Joseph
  • 117,725
  • 30
  • 181
  • 234
0

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

Simon
  • 168
  • 6
  • 2
    Why are your values strings? – Bergi May 09 '13 at 23:20
  • @Simon I am trying to use your code, but for unknown reasons it does not work. Am i missing something anyone? – Augusto May 10 '13 at 01:15
  • @Bergi Because I wasn't paying attention. (_fixed the code and added a working JSFiddle_) – Simon May 10 '13 at 11:53
  • @Simon, your code still does not work. I got it working differently on my end, but one thing is that every time i enter 3, 5, 7 I get a random 10000000002 answer, I dont know why? – Augusto May 10 '13 at 17:30
0

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

Xotic750
  • 22,914
  • 8
  • 57
  • 79
  • This code thats the work, but it is hard to follow. Thank you very much. – Augusto May 10 '13 at 13:52
  • I don't think you will find many solutions much simpler. Though I'm sure if it had comments then you may find it easier, or someone that was telling you what was going on line for line. – Xotic750 May 10 '13 at 14:03