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.
Related
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>
I've made this code to make a game that counts the number of clicks on the moving image .. but i can't make the Countdown or the counter .. i want when the user press start the game an countdown begins .. and every click on the image the number in (the counter) increased by one .. Thnx
var x_position = 0 ;
var theSpace = document.getElementById("gamespace");
var textt=document.getElementById("text");
var theMission = document.createTextNode(" - Press the tree as fast as you can ");
var theTree = document.createElement("img");
var moving;
function movingf() {
theSpace.appendChild(theTree);
theTree.style.left=Math.floor(Math.random() * 401) + "px";
theTree.style.right=Math.floor(Math.random() * 401) + "px";
theTree.style.top=Math.floor(Math.random() * 401) + "px";
theTree.style.bottom=Math.floor(Math.random() * 401) + "px";
moving=setTimeout(movingf,500);
theTree.addEventListener("click",theCounter);
}
function theGame() {
textt.style.clear="both";
theTree.setAttribute("src","http://franklinccc.org/wp-content/uploads/2014/03/ccc-tree-logo.jpg");
theTree.style.position="absolute";
theSpace.appendChild(theTree);
textt.appendChild(theMission);
moving=setTimeout(movingf,50);
theTree.onclick = theCounter();
}
function theCounter() {
var time = 0;
time = time + 1 ;
var theCount = document.getElementById("times").innerHTML=time;
}
#gamespace{
border:2px solid black ;
width:500px;
height:500px;
top:215px;}
p{position:absolute;
border:1px solid black;}
button{position:absolute;
top:60px;}
#here{position:absolute;
top:45px;
}
<h1> PICTURE GAME .. </h1>
<button id="start" onclick="theGame()"> Press here to start the game</button>
<div id="here">
<form action="/action_page.php" id="here">
The countdown :
<input type="text" name="firstname" value="0" >
The counter :
<input type="text" name="lastname" value="0">
</form>
</div>
<p id="text" style="top:170px"></p>
<div id="gamespace" style="position:absolute"> </div>
You have an error in your javascript :
"message": "Uncaught TypeError: Cannot set property 'innerHTML' of null",
here :
var theCount = document.getElementById("times").innerHTML=time;
You have no element with the id = "times", so if you want the <p> element to contain the count, change the line to :
var theCount = document.getElementById("text").innerHTML=time;
Also, theCounter() function should be like this :
function theCounter() {
time = time + 1 ;
document.getElementById("text").innerHTML=time;
}
var x_position = 0 ;
var theSpace = document.getElementById("gamespace");
var textt=document.getElementById("text");
var theMission = document.createTextNode(" - Press the tree as fast as you can ");
var theTree = document.createElement("img");
var moving ;
var time = 0;
function movingf() {
theSpace.appendChild(theTree);
theTree.style.left=Math.floor(Math.random() * 401) + "px";
theTree.style.right=Math.floor(Math.random() * 401) + "px";
theTree.style.top=Math.floor(Math.random() * 401) + "px";
theTree.style.bottom=Math.floor(Math.random() * 401) + "px";
moving=setTimeout(movingf,500);
theTree.addEventListener("click",theCounter);
}
function theGame() {
textt.style.clear="both";
theTree.setAttribute("src","http://franklinccc.org/wp-content/uploads/2014/03/ccc-tree-logo.jpg");
theTree.style.position="absolute";
theSpace.appendChild(theTree);
textt.appendChild(theMission);
moving=setTimeout(movingf,50);
theTree.onclick = theCounter();
}
function theCounter() {
time = time + 1 ;
document.getElementById("text").innerHTML=time;
}
#gamespace {
border: 2px solid black ;
width: 500px;
height: 500px;
top: 215px;
}
p {
position: absolute;
border: 1px solid black;
}
button {
position: absolute;
top: 60px;
}
#here {
position: absolute;
top: 45px;
}
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<body>
<h1> PICTURE GAME .. </h1>
<button id="start" onclick="theGame()"> Press here to start the game</button>
<div id="here">
<form action="/action_page.php" id="here">
The countdown :
<input type="text" name="firstname" value="0" >
The counter :
<input type="text" name="lastname" value="0">
</form>
</div>
<p id="text" style="top:170px"></p>
<div id="gamespace" style="position:absolute"> </div>
</body>
You were trying to reset your counter inside the theCounter function each time it was called, also tried to set innerHTML of element with id that was not in your markup. After fixing this this you can use setInterval to implement timer countdown:
var x_position = 0 ;
var theSpace = document.getElementById("gamespace");
var textt=document.getElementById("text");
var theMission = document.createTextNode(" - Press the tree as fast as you can ");
var theTree = document.createElement("img");
var moving;
function movingf() {
theTree.style.left=Math.floor(Math.random() * 401) + "px";
theTree.style.right=Math.floor(Math.random() * 401) + "px";
theTree.style.top=Math.floor(Math.random() * 401) + "px";
theTree.style.bottom=Math.floor(Math.random() * 401) + "px";
}
var clicks = 0, gameTimer, movingfTimer, timeleft;
theSpace.appendChild(theTree);
function theGame() {
clicks = 0;
timeleft = 30;
document.getElementById("times").value = clicks;
document.getElementById("countdown").value = timeleft;
textt.style.clear="both";
theTree.setAttribute("src","http://franklinccc.org/wp-content/uploads/2014/03/ccc-tree-logo.jpg");
theTree.style.position="absolute";
theSpace.appendChild(theTree);
textt.appendChild(theMission);
theTree.addEventListener("click", theCounter);
movingf();
clearInterval(movingfTimer);
clearInterval(gameTimer);
movingfTimer = setInterval(movingf, 500);
gameTimer = setInterval(function(){
timeleft--;
document.getElementById("countdown").value = timeleft;
if(timeleft <= 0){
clearInterval(gameTimer);
clearInterval(movingfTimer);
theTree.removeEventListener("click", theCounter);
}
}, 1000);
}
function theCounter() {
clicks++;
document.getElementById("times").value = clicks;
}
#gamespace {
border:2px solid black ;
width:500px;
height:500px;
top:215px;
}
p {
position:absolute;
border:1px solid black;
}
button {
position:absolute;
top:60px;
}
#here {
position:absolute;
top:45px;
}
<h1> PICTURE GAME .. </h1>
<button id="start" onclick="theGame()"> Press here to start the game</button>
<div id="here">
<form action="/action_page.php" id="here">
The countdown :
<input type="text" name="countdown" id="countdown" />
The counter :
<input type="text" name="times" id="times" value="0" />
</form>
</div>
<p id="text" style="top:170px"></p>
<div id="gamespace" style="position:absolute"> </div>
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.
i want to take input from user(number) and display image as many times as number.If user inputs 5 then the image should be displayed 5 times next to each other with corresponding number below the images-Below 1st image '1' 2nd Image '2'.Basically putting this table in loop.
<HTML>
<BODY>
<TABLE>
<TR>
<TD>
<IMG SRC="C:/Users/User/Desktop/RE/G.JPG">
</TD>
</TR>
<TR><TD ALIGN="CENTER">1</TD>
</TABLE>"
</BODY>
</HTML>
You can use jQuery for this task and write a function that generates HTML with a dynamic value:
Complete Solution
<HTML>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.3/jquery.min.js"></script>
<script type="text/javascript">
function generateTable(number) {
return "<table><tr><td>" +
"<img src='C:/Users/User/Desktop/RE/G.JPG'></td></tr><tr><td align='center'>" +
number +
"</td></table>";
}
$(function(){
var userInput = 3;
for (var i = 0; i < userInput; i++) {
$('#dynamic').append(generateTable(i + 1));
}
});
</script>
</head>
<body>
<div id='dynamic'></div>
</body>
</html>
You can add an input and a button to trigger the function.
You could also check if the inserted value is actually a number or not.
$(document).on('click', '#add', function() {
var that = $(this);
var times = parseInt($('#times').val());
for (i=1;i<=times;i++) {
$('#table-wrp').append('<table class="table-times"><tbody><tr><td><img src="http://code52.org/aspnet-internationalization/icon.png" /></td></tr><tr><td>' + i + '</td></tr></tbody></table>');
}
});
$(document).on('input', '#times', function() {
var that = $(this);
var value = that.val();
if ((value != '' || value != false) && !isNaN(value)) {
$('#add').prop('disabled', false);
} else {
$('#add').prop('disabled', true);
}
});
#table-wrp {
height: 80px;
}
.table-times {
width: 100px;
height: 80px;
float: left;
border-collapse: collapse;
}
.table-times td {
border: 1px solid #d8d8d8;
text-align: center;
}
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
<input type="textbox" id="times" />
<button id="add" disabled>Add</button>
<div id="table-wrp"></div>
Or for a pure javascript version of Pugazh's answer
var tab = "<div></div>";
var num = prompt("Enter a number");
for(i = 0; i < num; i++){
document.getElementById('tab').innerHTML += "<div><div><img src='http://placehold.it/150x150'></div><div></div></div>";
}
img{
float: left;
box-shadow: 5px 5px 10px rgba(0,0,0,0.4);
height: 100px;
width: 100px;
margin: 10px;
}
<div id="tab"></div>
This will work just as well, but doesn't require jQuery as well.
<HTML>
<BODY>
<div id="tbl"></div>
</BODY>
</HTML>
<script>
var num = prompt("Enter a number");
var div=document.getElementById("tbl");
var l1='',l2="";
for(i=0;i<num;i++)
{
l1 += '<td><img src="C:/Users/User/Desktop/RE/G.JPG"></td>';
l2 += '<td>'+i+'</td>';
}
div.innerHTML = "<table><tr>"+l1+"</tr><tr>" + l2 + "</tr></table>";
</script>
Try this
$(function() {
var tab = "<div></div>";
var num = prompt("Enter a number");
for (i = 0; i < num; i++) {
$("#tab").append("<div class='left'><div><img src='http://placehold.it/150x150'></div><div>" + (i + 1) + "</div></div>");
}
});
div.left {
display: inline-block;
margin-right: 5px;
}
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
</head>
<body>
<div id="tab">
</div>
</body>
</html>
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