How to add numbers value in ONE input text? - javascript

I have coded and used for loop but only works if I use multiple Input text.
I want to achieve:
Every time I input number on one Input text and hit the buttons "add" or "deduct, I want the total below will keep updating while adding or deducting.
let total = 0;
for(var i=0; i<priceTrim.length; i++){
if(parseInt(priceTrim[i].value))
total += parseInt(priceTrim[i].value);
}
document.getElementById('total').value = total;
Please see the screenshot

What I understand, that you want to enter the name and price of item and then by add or deduct button, perform add or subtract operation. Plus you also want to manage the Total Value.
I create a program through your screenshot. Code is written below.
// Selecting the Elements from Html
Item_Name = document.getElementById("Item_Name");
var Price = document.getElementById("Price");
var Add = document.getElementById("Add");
var Deduct = document.getElementById("Deduct");
var Name_Here = document.getElementById("name_here");
var Price_Here = document.getElementById("price_here");
var Total = document.getElementById("Total");
var Total_Value = 0;
// Get and Set the values
Add.onclick = function(){
Name_Here.innerText = Item_Name.value;
Price_Here.innerText = Price.value;
Total_Value += parseInt(Price.value);
Total.innerText = Total_Value;
}
Deduct.onclick = function(){
Name_Here.innerText = Item_Name.value;
Price_Here.innerText = Price.value;
Total_Value -= parseInt(Price.value);
Total.innerText = Total_Value;
}
.flex_container{
display: flex;
justify-content: center;
}
.container{
width: 300px;
min-height: 220px;
border: 1px solid black;
padding: 10px;
}
button{
margin: 12px 0px;
}
.Span_Header{
display: flex;
justify-content: space-between;
}
input{
width: 100%;
margin: 8px 0px;
}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<div class="flex_container">
<div class="container">
<span>Item name</span><br>
<input type="text" name="item_name" id="Item_Name" placeholder="Item name"><br>
<span>Price</span><br>
<input type="number" name="price" id="Price" placeholder="Price"><br>
<button id="Add">Add</button>
<button id="Deduct">Deduct</button>
<div class="Span_Header">
<span>Item name</span>
<span>Price</span>
</div>
<hr>
<div class="Span_Header">
<span id="name_here">Name Here</span>
<span id="price_here">Price Here</span>
</div>
<hr>
<div class="Total_div">
<span>Total: </span>
<span id="Total"></span>
</div>
</div>
</div>
</body>
</html>

Please include all of your code if you would like an answer. What is priceTrim?
Are you trying to loop through a number of textbox values? If so you will have to use the querySelectorAll domElement method to loop as it returns an array type of all the text boxes , then you can specify what it is you want to do with that information in the function.
Also your if statement syntax is all wrong. You have no code block for code to perform if your testing condition returns true.
Please put in all the code and try ans explain what exactly it is you are trying to achieve? I feel like you’ve given half a story!

Related

JavaScript DOM table manipulation

First Problem
How to modify the function cut() to apply "line-through" to all td elements not for only the first.
Second Problem
When I generate the table I don't know what I'm missing in this.details to automatically generate the th of the table only one time (not to display in html like in the code below) because I tried
this.details = `<tr>
<th>Item description<\th>
<th>Action<\th>
<td>${this.item}</td>
<td>${this.action}</td>
</tr>`;
and the th is generate for each td.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link rel="stylesheet" href="style.css">
<title>list</title>
</head>
<body>
<h2>list</h2>
<div class="container">
<input type="text" name="item" id="item">
<label for="item"></label>
<input type="button" value="Add item" class="addBtn" id="add">
</div>
<div class="container" id="sort">
<input type="button" value="Sort asc" class="btn">
<input type="button" value="Sort desc" class="btn">
</div>
<div class="tableData" id="table">
<table id="display-none">
<tr>
<th class="show-succes">product</th>
<th class="show-succes">mark</th>
</tr>
</div>
<script src="app.js"></script>
</body>
</html>
function Item(item, action, table) {
this.item = item;
this.action = `<input type="button" value="Mark as buyed" class="newBtn" id="buton" onclick="cut()" `;
this.details = `<tr>
<td>${this.item}</td>
<td>${this.action}</td>
</tr>`;
this.table = table;
this.addToTable = function () {
this.table.innerHTML += this.details;
};
}
const addBtn = document.getElementById('add');
addBtn.addEventListener('click', addNewItem);
function addNewItem() {
const items = document.getElementById('item').value;
const actions = 'mark as buyed'
const myTable = document.getElementById('display-none');
const item = new Item(items, actions, myTable);
item.addToTable();
}
function cut() {
let el = document.querySelector("td");
el.style.textDecoration = "line-through";
}
*{
margin: 0px;
padding: 0px;
box-sizing: border-box;
text-decoration: none;
}
h2 {
text-align: center;
padding: 60px ;
}
input[type="text"]{
margin-right: 20px;
}
label{
padding: 15px;
}
.btn{
padding: 5px;
margin-top: 20px;
margin-right: 10px;
}
#sort{
margin-left: -90px;
}
.container{
display: flex;
justify-content: center;
}
#table{
width: 40%;
text-align: center;
margin-left: 650px;
margin-top: 20px;
}
Your approach is much more involved than necessary and really wouldn't do you any good to try to fix it.
See comments inline below for the most simple approach.
// Get reference to the elements you'll use
// over and over, just once.
const input = document.getElementById("item");
const tbl = document.querySelector("table");
const add = document.querySelector(".addBtn");
// Add an event handler for the add button click
add.addEventListener("click", function(){
let row = tbl.insertRow(); // Add a row to the table
let itemCell = row.insertCell(); // Add a td to the row
itemCell.textContent = input.value; // Put the input value in the td
let actionCell = row.insertCell(); // Add a second td to the row
let chk = document.createElement("input"); // Create a new input
chk.type = "checkbox"; // Make the input a checkbox
chk.value = "bought"; // Set a value for the checkbox
// Set up an event handler for the new checkbox
chk.addEventListener("click", function(){
// Find the nearest ancestor tr and then query it
// for the first td in it. Then toggle the use of the
// "strike" CSS class to add or remove strikethrough.
this.closest("tr").querySelector("td").classList.toggle("strike");
});
actionCell.appendChild(chk); // Add the checkbox to the td
input.value = ""; // Clear out the textbox
tbl.classList.remove("hidden"); // Show the table
});
body {
font-family:Calibri, Helvetica, Arial;
}
h1 {
font-size:1.8em;
}
div {
margin:1em;
}
.strike {
text-decoration-line: line-through;
}
.hidden {
display:none;
}
<h1>SHOPPING LIST</h1>
<div class="addItems">
<input type="text" id="item">
<input type="button" value="Add item" class="addBtn">
</div>
<table class="hidden">
<tr>
<th>Item</th>
<th>Bought?</th>
</tr>
</table>

Span value inside a style value

this maybe a very stupid question, but is this possibe ?
well i have a sort of a slider on a html page.
this is what it shows up like now:
<p>Illustrator</p>
<div class="w3-light-grey w3-round-xlarge w3-small">
<div class="w3-container w3-center w3-round-xlarge w3-teal" style="width:75%">75%</div>
</div>
This shows up a bar,
well what want to achieve is if its possible to change that value 75% to my script data :
style="width:75%">
like i have a script, it retrieves values from my server:
var input = "10;11;15";
var arr = input.split(";");
document.getElementById("humid").innerHTML = (arr[0 ]);
this shows up my data just normal
<span id="humid">0</span>
what i want to do is something like this, but i don't know how:
I want this value from style="width:75%"> to be the humid value.
so if my humid value is 50% the width goes 50%
i did try this but no result
style="width:humid+%">
or style="width:(humid)+%">
i'm still learning,
regards
<!DOCTYPE html>
<html>
<title>TESt</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" href="https://www.w3schools.com/w3css/4/w3.css">
<link rel='stylesheet' href='https://fonts.googleapis.com/css?family=Roboto'>
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css">
<style>
html,body,h1,h2,h3,h4,h5,h6 {font-family: "Roboto", sans-serif}
</style>
<body class="w3-light-grey">
<p>Original</p>
<div class="w3-light-grey w3-round-xlarge w3-small">
<div class="w3-container w3-center w3-round-xlarge w3-teal" style="width:75%">75%</div>
</div>
<p>Media</p>
<div class="w3-light-grey w3-round-xlarge w3-small">
<div class="w3-container w3-center w3-round-xlarge w3-teal" style="#humid">0</div>
</body>
<script>
var input = "10;11;15";
var arr = input.split(";");
//alert(arr[1 ]);
document.getElementById("humid").innerHTML = (arr[0]);
document.getElementById("temp").innerHTML = (arr[1 ]);
document.getElementById("uv").innerHTML = (arr[2 ]);
</script>
</html>
Retrieve my input:
function readForestall() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("ForestAll").innerHTML =
this.responseText;
}
};
xhttp.open("GET", "readFORESTALL", false);
xhttp.send();
}
setInterval(function() {
readForestall();
}, 5000);
If I understand your question right, you want to change the width of an element based on a variable you receive. In that case you can change the inline style with JavaScript. You just need to grab the element and set the style by assigning values to the properties of the element's style property.
If you want to change the width, you can use the following:
element.style.width = '50%'
It sets the width to 50%. You can also include a variable like this:
const width = 50
element.style.width = `${width}%`
I've created a snippet below where you can set the value by using an input and it updates both the width and the content of that div. You can click on the "Run code snippet button" and see the result in live.
const barLeft = document.querySelector('#bar-left');
const barRight = document.querySelector('#bar-right');
const input = document.querySelector('[name="width"]');
const error = document.querySelector('.error');
input.addEventListener('input', (e) => {
const widthLeft = Number(e.target.value);
const widthRight = 100 - widthLeft;
if (widthLeft < 0 || widthLeft > 100) {
error.textContent =
"We don't do that here. Width must be between 0 and 100.";
return;
}
error.textContent = '';
barLeft.textContent = `${widthLeft}%`;
barLeft.style.width = `${widthLeft}%`;
barRight.textContent = `${widthRight}%`;
barRight.style.width = `${widthRight}%`;
});
body {
font-family: sans-serif;
margin: 0;
text-align: center;
}
.outer {
display: flex;
margin-bottom: 2rem;
}
.inner {
background-color: lightcoral;
box-shadow: 0 -4px 0 rgba(0, 0, 0, 0.2) inset;
height: 100%;
padding: 1rem;
}
.inner--blue {
background-color: lightblue;
}
.controls {
margin-bottom: 1rem;
}
input {
font-family: inherit;
font-size: inherit;
padding: 0.5rem 1rem;
}
.error {
color: #d32f2f;
}
<div class="outer">
<div class="inner" id="bar-left" style="width: 75%">75%</div>
<div class="inner inner--blue" id="bar-right" style="width: 25%">25%</div>
</div>
<div class="controls">
<label for="width">First bar's width:</label>
<input type="number" name="width" id="width" min="5" max="95" value="75" />
</div>
<div class="error"></div>
Update: Updated your example below. Make sure you close your tags, and check out how to add ids to elements.
<body class="w3-light-grey">
<p>Media</p>
<div class="w3-light-grey w3-round-xlarge w3-small">
<div class="w3-container w3-center w3-round-xlarge w3-teal" id="humid">
0
</div>
</div>
div>
<script>
var input = '10;11;15';
var arr = input.split(';');
// update the content of the div with ID "humid"
document.getElementById('humid').textContent = arr[0];
// change the width of the div with ID "humid"
document.getElementById('humid').style.width = `${arr[0]}%`;
</script>
</body>
Tranq,
i am not exactly sure why you would want to call the width from an array and use DOM when you can simply use CSS to accomplish this with #media instead. correct me if i am wrong, but you're just trying to adjust the width based on values of the current width of the device? this seems like a whole lot of work for what is a simple solution.
use something like to set the appropriate widths depending on the screen widths:
#media only screen and (max-width: 600px) {
#humid { width: 75%; }
}
also, it is likely you're not passing your array properly and it is returning NULL(0). you can check this via a debugger and ensure it is being passed properly. FireFox has a Great built in debugger for this. use CMD/CTRL+SHIFT+K to open the debugger in FireFox.
P.S. you are not passing the array properly. you're setting it to change the 'innerHTML' which changes everything inside of the
document.getElementById("humid").innerHTML = (arr[0 ]);
if you change "(arr[0 ]);" to something like "string" it will replace the value 0 to "string".

Input value not updating on page when changed

I have to do a web page for school that converts temperature between celsius and fahrenheit.
I tried to make it with 2 input boxes that change value based on the value of the other input box, when I write something on one of the input boxes for the first time it works, but then even though on the code the value changes, on the page it doesn't appear.
I am new to javascript and html in general and I don't know what I'm doing wrong.
This is the code:
function cambiagradi(x,y) {
if (document.getElementById(x).value == "Centigradi") {
document.getElementById(y).value = "Fahrenheit";
}
else {
document.getElementById(y).value = "Centigradi";
}
}
function Conversione(from,to,gradi) {
var x = document.getElementById(from).value;
if (document.getElementById(gradi).value == "Centigradi") {
document.getElementById(to).setAttribute("value", (x-32)*5/9);
}
else {
document.getElementById(to).setAttribute("value", (x*9/5)+32);
}
}
<html lang="it">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body style="background-color: #008080;">
<h1 style="text-align:center">Convertitore Temperatura</h1>
<div class="container" style="display:flex; justify-content: center">
<div style=" padding: 1%; ">
<p>
<input type="text" id="box1" oninput="Conversione('box1','box2','Gradi2')">
</p>
<p style="margin-left:10%">
<label for="Gradi1">Gradi</label>
<select id="Gradi1" onchange="cambiagradi('Gradi1','Gradi2')">
<option value="Centigradi">Centigradi</option>
<option value="Fahrenheit">Fahrenheit</option>
</select>
</p>
</div>
<div style=" padding: 1%; ">=</div>
<div style=" padding: 1%; ">
<p>
<input type="text" id="box2" oninput="Conversione('box2','box1','Gradi1')">
</p>
<p style="margin-left:10%">
<label for="Gradi2">Gradi</label>
<select id="Gradi2" onchange="cambiagradi('Gradi2','Gradi1')">
<option value="Fahrenheit">Fahrenheit</option>
<option value="Centigradi">Centigradi</option>
</select>
</p>
</div>
</div>
</body>
</html>
Thanks in advance!
You should just set the value of the element and all would work as expected.
The explanation you can find here.
function Conversione(from, to, gradi) {
const x = document.getElementById(from).value;
if (document.getElementById(gradi).value == "Centigradi") {
document.getElementById(to).value = ((x - 32) * 5) / 9;
} else {
document.getElementById(to).value = (x * 9) / 5 + 32;
}
}
Some explanations within the code. Tell me if you need more. It looks more complicated but it avoids inline JavaScript which is good :)
// Define your elements as variables first as you're going to use them multiple times :
const gradi1 = document.getElementById("Gradi1");
const gradi2 = document.getElementById("Gradi2");
const box1 = document.getElementById("box1");
const box2 = document.getElementById("box2");
// Now, always use gradi1, gradi2, box1 and box2 instead of document.getElementById ....
// Then, avoid INLINE JavaScript ! (onchange="")
// We're gonna add 'event listener' to your elements
gradi1.addEventListener("change", function(){
cambiagradi(this); // 'this' means you'll know which element triggered the event when calling the function
}, false);
gradi2.addEventListener("change", function(){
cambiagradi(this);
}, false);
box1.addEventListener("input", function(){
Conversione(this)
}, false);
box2.addEventListener("input", function(){
Conversione(this)
}, false);
// You passed 'this' previously, so its back here with the name you want (ex: ancora_this)
function cambiagradi(ancora_this) {
if (ancora_this.id == "Gradi1") {
if (ancora_this.selectedIndex == 0) { // 'selectedIndex' means selected option position in the dropdown menu (begins at 0)
gradi2.selectedIndex = 1;
} else {
gradi2.selectedIndex = 0;
}
} else {
if (ancora_this.selectedIndex == 1) {
gradi1.selectedIndex = 0;
} else {
gradi1.selectedIndex = 1;
}
}
}
function Conversione(ancora_this) {
var target, conv, unit;
if (ancora_this.id == "box1") {
target = box2;
unit = gradi1;
} else {
target = box1;
unit = gradi2;
}
if (unit.selectedIndex == 0) {
conv = (Number(ancora_this.value) * 9/5) + 32;
} else {
conv = (Number(ancora_this.value) - 32)*5/9;
}
target.value = conv;
}
body {
background-color: #008080
}
h1 {
text-align: center
}
.container {
display: flex;
justify-content: center
}
.container div {
padding: 1%;
}
<!DOCTYPE html>
<html lang="it">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<h1>Convertitore Temperatura</h1>
<div class="container">
<div>
<p>
<!-- type="number" is better because it only allows numbers -->
<input type="number" id="box1">
</p>
<p style="margin-left:10%">
<label for="Gradi1">Gradi</label>
<select id="Gradi1">
<option value="Centigradi" selected>Centigradi</option>
<option value="Fahrenheit">Fahrenheit</option>
</select>
</p>
</div>
<div>=</div>
<div>
<p>
<input type="number" id="box2">
</p>
<p style="margin-left:10%">
<label for="Gradi2">Gradi</label>
<select id="Gradi2">
<!-- I switched the order to have the same 'index' on both SELECT menus
Also, I added 'selected' to have a default selected unit at start -->
<option value="Centigradi">Centigradi</option>
<option value="Fahrenheit" selected>Fahrenheit</option>
</select>
</p>
</div>
</div>
</body>
</html>

How to make UI more responsive for other screen sizes?

I have an html page in which I have a textbox (Type your text) and TextArea list. I need to type into the textbox and then click Add button so that whatever is there in textbox goes to my TextArea list. I need to type in this below format in the textbox.
Name=Value
This textbox will be used by the user to quickly add Name Value pairs to the list which is just below that textbox. let's say if we type Hello=World in the above textbox and click add, then in the below list, it should show as
Hello=World
And if we again type ABC=PQR in the same textbox, then in the below list, it should show like this so that means it should keep adding new Name Value pair just below its original entry.
Hello=World
ABC=PQR
But if the syntax is incorrect like if it is not in Name=Value pair then it should not add anything to the list and instead show a pop up that wrong input format. Names and Values can contain only alpha-numeric characters. I also have three more buttons Sort by name, Sort by value and Delete button. Once I click either of these buttons, then it should sort entries in TextArea list using either name or value and delete entries as well. Now I have all above things working fine without any issues.
Here is my jsfiddle. I need to use plain HTML, CSS and Javascript, I don't want to use any library yet as I want to keep it simple as I am still learning. Now I am trying to see whether we can make UI more responsive like the UI should adjust based on what screen size is viewing it. For example, if viewed on a mobile phone (i.e. Android or iPhone), the page should automatically adjust to present the layout in a better way. This also applies to re-sizing the browser on desktop, and viewing the page on a tablet.
What are the changes I need to make in my CSS or HTML to make it more responsive? Any improvements I can make here? Since my UI is very simple so there should be some easy way or some improvements I can make here.
Below is my code:
<!DOCTYPE html>
<html>
<head>
<meta charset="UTF-8">
<title>Test</title>
<style type="text/css">
.main{
background:white;
padding: 35px;
border-radius: 5px;
}
#my-text-box {
font-size: 18px;
height: 1.5em;
width: 585px;
}
#list{
width:585px;
height:300px;
font-size: 18px;
}
.form-section{
overflow:hidden;
width:700px;
}
.fleft{float:left}
.fright{float:left; padding-left:15px;}
.fright button{display:block; margin-bottom:10px;}
html, body {
height: 100%;
font-family: "Calibri";
font-size: 20px;
}
html {
display: table;
margin: auto;
}
body {
display: table-cell;
vertical-align: middle;
background-color: #5C87B2;
}
</style>
<script language="javascript" type="text/javascript">
document.getElementById('add').onclick = addtext;
function addtext() {
var nameValue = document.getElementById('my-text-box').value;
if (/^([a-zA-Z0-9]+=[a-zA-Z0-9]+)$/.test(nameValue)){
var x = document.getElementById("list");
var option = document.createElement("option");
option.text = nameValue;
x.add(option);
}
else
alert('Incorrect Name Value pair format.');
}
document.getElementById('btnDelete').onclick = deleteText;
function deleteText(){
var myList = document.getElementById('list');
var i;
for (i = myList.length - 1; i>=0; i--) {
if (myList.options[i].selected) {
myList.remove(i);
}
}
}
document.getElementById('sortByValue').onclick = sortByValue;
function sortByValue(){
var myList = document.getElementById('list');
var values = new Array();
for (var i=0;i<myList.options.length;i++) {
values[i] = myList.options[i].text;
}
values.sort(function(a, b){
if(a != "" && b != ""){
return a.split('=')[1].localeCompare(b.split('=')[1])
} else {
return 0
}
});
clearList(myList);
fillList(myList, values);
}
document.getElementById('sortByName').onclick = sortByName;
function sortByName(){
var myList = document.getElementById('list');
var values = new Array();
for (var i=0;i<myList.options.length;i++) {
values[i] = myList.options[i].text;
}
values.sort(function (a, b){
if(a != "" && b != ""){
return a.split('=')[0].localeCompare(b.split('=')[0])
} else {
return 0
}
});
clearList(myList);
fillList(myList, values);
}
function clearList(list) {
while (list.options.length > 0) {
list.options[0] = null;
}
}
function fillList(myList, values){
for (var i=0;i<values.length;i++) {
var option = document.createElement("option");
option.text = values[i];
myList.options[i] = option;
}
}
</script>
</head>
<body>
<div class = 'main'>
<h3>Test</h3>
<label for="pair">Type your text</label></br>
<div class="form-section">
<div class="fleft">
<input type='text' id='my-text-box' value="Name=Value" />
</div>
<div class="fright">
<button type="button" id='add' onclick='addtext()'>Add</button>
</div>
</div>
<label for="pairs">Name/Value Pair List</label></br>
<div class="form-section">
<div class="fleft">
<select id="list" multiple></select>
</div>
<div class="fright">
<button type="button" id='sortByName' onclick='sortByName()'>Sort by name</button>
<button type="button" id='sortByValue' onclick='sortByValue()'>Sort by value</button>
<button type="button" id='btnDelete' onclick='deleteText()'>Delete</button>
<button type="button">Show XML</button>
</div>
</div>
</div>
</body>
</html>
W3 have a number of resources on responsive web design:
http://www.w3schools.com/html/html_responsive.asp
http://www.w3schools.com/css/css_responsive_intro.asp
Without using PHP to detect the browser/user agent, your responsive design will typically involve ensuring the site is more fluid and flowing, allowing for changing browser widths (as in the first example above) and/or by delivering differing stylesheets depending on the viewport size and media type in CSS (second example).

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