How can I add old input value to new input value? - javascript

let currencySymbol = '$';
document.querySelector('.pay').addEventListener('click', (e) => {
e.preventDefault();
// Get input cash received field value, set to number
let amount = document.querySelector('.received').value;
amount *= 1;
// Set cashReturn to return value of pay()
let cashReturn = pay(amount);
let paymentSummary = document.querySelector('.pay-summary');
let div = document.createElement('div');
// If total cash received is greater than cart total thank customer
// Else request additional funds
if (cashReturn >= 0) {
div.innerHTML = `
<p>Cash Received: ${currencySymbol}${amount}</p>
<p>Cash Returned: ${currencySymbol}${cashReturn}</p>
<p>Thank you!</p>
`;
} else {
// reset cash field for next entry
document.querySelector('.received').value = '';
div.innerHTML = `
<p>Cash Received: ${currencySymbol}${amount}</p>
<p>Remaining Balance: ${cashReturn}$</p>
<p>Please pay additional amount.</p>
<hr/>
`;
}
paymentSummary.append(div);
});
let totalPaid = 0;
function pay(totalPaid) {
let cartSum = 50; //using a dummy value for snippet
return totalPaid - cartSum;
}
.checkout-container {
max-width: 34em;
padding: 2em;
background: #efefef;
}
<div class="checkout-container">
<h2>Checkout</h2>
<div class="checkout">
<div class="cart-total"></div>
<form>
<label>Enter Cash Received:</label>
<input class="received" type="text">
<button class="pay">Submit</button>
</form>
<h3>Receipt</h3>
<div class="pay-summary"></div>
</div>
</div>
I'm implementing a simple cash register where user enters how much they paid into an input field, and it will subtract it from the total cost of the items. If the number returned is positive, it shows that the customer wil be given back the remaining change. If it's a negative value, the customer needs to add more money into the input field, which should be summed with their previous input.
Right now, the previous value is not being added to the new value:
After I input the remaining $15, there should be 0 remaining balance.

If you mean to type an amount of cash received more than once, you need to keep track of the amount of money received so far.
There are multiple ways to achieve that, here I opted for keeping track of it inside the value of an added input element.
In my demo the function cartTotal() always returns 78.45 as the amount to pay, and to reset the amount of money received so far, you just need to click the reset button so that the corresponding input value will be set back to zero.
function pay(totalPaid){
let cartSum = cartTotal();
return totalPaid - cartSum;
}
//Arbitrary number
function cartTotal(){
return 78.45;
}
function resetGame(){
document.getElementById('sofar').value = 0;
document.getElementById('received').value = 0;
document.getElementById('cashreturn').value = 0;
}
document.querySelector('.pay')
.addEventListener('click', (e) => {
e.preventDefault();
// Get input cash received field value, set to number
const amount = parseFloat( document.getElementById('received').value );
//**Here updates the amount received so far
const receivedSoFar = parseFloat( document.getElementById('sofar').value );
document.getElementById('sofar').value = receivedSoFar + amount;
// Set cashReturn to return value of pay()
const cashReturn = pay(amount + receivedSoFar);
document.getElementById('cashreturn').value = cashReturn.toFixed(2);
});
body{
font-family: sans-serif;
}
input, button{
padding: .2rem;
width: 5rem;
font-size: 15px;
}
input[disabled]{
outline: none;
border: none;
font-size: 20px;
}
button{
cursor: pointer;
}
<label>Enter cash:</label>
<input type="text" id="received">
<button class="pay">PAY</button>
<hr>
<label>Received so far:</label>
<input type="text" id="sofar" readonly disabled value="0">
<br>
<label>Cash return:</label>
<input type="text" id="cashreturn" readonly disabled value="0">
<br>
<button onclick="resetGame();">RESET</button>

Your amount variable only represents the last input. Any previous submitted amounts are lost. To fix this, define amount as a global variable, and add to that what the user has entered.
So change this part:
document.querySelector('.pay').addEventListener('click', (e) => {
e.preventDefault();
// Get input cash received field value, set to number
let amount = document.querySelector('.received').value;
amount *= 1;
to:
let amount = 0; // <--- define here so to accumulate paid amounts
document.querySelector('.pay').addEventListener('click', (e) => {
e.preventDefault();
// Get input cash received field value, set to number
let paid = document.querySelector('.received').value;
amount += +paid; // <--- accumulate
Your adapted snippet:
let currencySymbol = '$';
let amount = 0; // <--- define here so to accumulate paid amounts
document.querySelector('.pay').addEventListener('click', (e) => {
e.preventDefault();
// Get input cash received field value, set to number
let paid = document.querySelector('.received').value;
amount += +paid; // <--- accumulate
// Set cashReturn to return value of pay()
let cashReturn = pay(amount);
let paymentSummary = document.querySelector('.pay-summary');
let div = document.createElement('div');
// If total cash received is greater than cart total thank customer
// Else request additional funds
if (cashReturn >= 0) {
div.innerHTML = `
<p>Cash Received: ${currencySymbol}${amount}</p>
<p>Cash Returned: ${currencySymbol}${cashReturn}</p>
<p>Thank you!</p>
`;
} else {
// reset cash field for next entry
document.querySelector('.received').value = '';
div.innerHTML = `
<p>Cash Received: ${currencySymbol}${amount}</p>
<p>Remaining Balance: ${cashReturn}$</p>
<p>Please pay additional amount.</p>
<hr/>
`;
}
paymentSummary.append(div);
});
let totalPaid = 0;
function pay(totalPaid) {
let cartSum = 50; //using a dummy value for snippet
return totalPaid - cartSum;
}
.checkout-container {
max-width: 34em;
padding: 2em;
background: #efefef;
}
<div class="checkout-container">
<h2>Checkout</h2>
<div class="checkout">
<div class="cart-total"></div>
<form>
<label>Enter Cash Received:</label>
<input class="received" type="text">
<button class="pay">Submit</button>
</form>
<h3>Receipt</h3>
<div class="pay-summary"></div>
</div>
</div>

Related

How to make a text appear with a desired innerHTML using javascript/jquery

There is a button and a h2 tag. the h2 tag has its visibilty=hidden.
When the button is clicked, I want to call a function that calculates the cost and changes the innerHTML of h2 accordingly and then changes its visibility=visible.
HTML:
<main class="form-signin">
<form>
<div class="card">
<label for="inputAdult">Enter number of adults</label><input type="number" id="inputAdult" class="form-control" placeholder="No. of adults" required>
<label for="inputChildren">Enter number of children (4-12yo)</label><input type="number" id="inputChildren" class="form-control" placeholder="No. of children" required>
<button type="button" onclick="showCost()" id="btn3">Calculate my cost</button>
<h2 class="changeCost">Your total cost: $0</h2>
</div>
</form>
</main>
JavaScript / jQuery :
$("h2").css("visibility","hidden");
function calculateCost(){
var a = $("#inputAdult").val();
var c = $("#inputchildren").val();
if (((a+c)%3==0)||((a+c)%3==1)) {
var rooms = (a+c)/3;
}
else {
var rooms = ((a+c)/3)+1;
}
var cost = rooms*300;
return cost;
}
function showCost() {
var display = "Your total cost is: $" + calculateCost();
var x = $("h2");
x.value = display;
$("h2").css("visibility","visible");
}
Try x.text(display) instead of setting value. That changes the innerText of the element. If you'd like to set its HTML content, use x.html(display).
The value accessor is used for plain HTMLElement objects, not for jQuery-wrapped objects.
Apart from this, you should never access a tag solely by its tag name. Always give it some kind of class name or ID. You already gave it the changeCost class, so you could do $("h2.changeCost") rather than $("h2").
To avoid getting NaN do the following:
Javascript is case sensitive so replace line
var c = $("#inputchildren").val();
with
var c = $("#inputChildren").val();
I would also consider declaring rooms variable from if and else scope so it is accessible on calculations: see full function bellow:
function calculateCost(){
var a = $("#inputAdult").val();
var c = $("#inputChildren").val();
var rooms = 0;
if (((a+c)%3==0)||((a+c)%3==1)) {
rooms = (a+c)/3;
}
else {
rooms = ((a+c)/3)+1;
}
var cost = rooms*300;
return cost;
}

How to check and return a message if no value entered

I'm still learning and am trying to simply take a number from an input, add 7 to it, and then display it on the webpage. It all works fine, but what I don't like is if you hit "submit" without entering a number, the HTML field shows "NaN" vs. a custom message, which is what I'd like to do.
Here's the code I have so far. What am I missing to capture that nothing was entered and return a different message?
function add7() {
let number = document.getElementById('num').value;
let addition = 7;
if (isNaN(number)){
document.getElementById("add").innerHTML ="Please enter a value";
}
else {
let original = parseInt(number,10);
num = addition + original;
document.getElementById("add").innerHTML = num;
}
}
<div class="add">
Add 7 to the number <br>
<input type="number" id="num">
<button onclick="add7()">Press Button</button>
<hr>
<p id="add"></p>
</div>
That is because an empty string actually returns true when passed to isNaN(), i.e. isNaN('') returns true.
To do that, you can simply move the check to the final step, a.k.a. evaluate the num variable instead:
function add7() {
let number = document.getElementById('num').value;
let addition = 7;
let original = parseInt(number, 10);
let num = addition + original;
if (isNaN(num)) {
document.getElementById("add").innerHTML = "Please enter a value";
return;
}
document.getElementById("add").innerHTML = num;
}
<div class="add">
Add 7 to the number <br>
<input type="number" id="num">
<button onclick="add7()">Press Button</button>
<hr>
<p id="add">
</p>
</div>
Alternatively, you can also simply parse the input element's value directly: it will inform you if it is not a number right away:
function add7() {
let number = parseInt(document.getElementById('num').value, 10);
if (isNaN(number)) {
document.getElementById("add").innerHTML = "Please enter a value";
return;
}
let addition = 7;
let num = addition + number;
document.getElementById("add").innerHTML = num;
}
<div class="add">
Add 7 to the number <br>
<input type="number" id="num">
<button onclick="add7()">Press Button</button>
<hr>
<p id="add">
</p>
</div>

Creating a function that removes HTML elements

I have this code from #Snowmonkey
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(function() {
$("#submitBtn").on("click", submitted);
// Created an 'add new row' button, which non-destructively adds a row to the container.
$(".add-row-btn").on("click", function(evt) {
evt.preventDefault();
evt.stopPropagation();
$(".container").append(createNewRow());
})
// When the user chooses a different number, completely reset all the rows?
$('#amount').on('change', function() {
// Save a reference to the row container.
var containerEl = $(".container");
// wipe out completely the contents of the container.
containerEl.empty();
// get the number of rows to be created.
var startingNumberOfLines = parseInt($("#amount").val());
// loop the number of times requested, and append a new row each time.
// createNewRow() is defined below.
for (var i = 0; i < startingNumberOfLines; i++) {
$(".container").append(createNewRow());
}
});
// Start with an initial value.
$(".add-row-btn").trigger("click");
})
/*****
* createNewRow() -- function to create a new row, composed of a text input,
* and two labels containing number inputs.
*****/
var createNewRow = function() {
/****
* first, we'll define all the elements that will be placed
* in this row -- the text input, the labels and the inputs.
****/
var lineTitleEl = $("<input>").attr("placeholder", "enter text here")
.addClass("line-title");
var labelEl = $("<label>");
var inputEl = $("<input>").attr("step", "0.05").attr("type", "number")
.addClass("line-number");
// The firstNumberEl is a label containing an input. I can simply
// clone my label el, and input el, and use them. Don't need to,
// but i CAN.
var firstNumberEl = labelEl.clone();
firstNumberEl.text("number1: ").attr("class", "first-number-el").append(inputEl.clone());
var secondNumberEl = labelEl.clone();
secondNumberEl.text("number2: ").attr("class", "second-number-el").append(inputEl.clone());
// Now create the row, which is a div containing those elements.
var newRowEl = $("<div>").append(lineTitleEl, firstNumberEl, secondNumberEl);
// Simply return that row -- the user can send it to the console or
// can append it wherever they like.
return newRowEl;
}
/******
* submitted() -- function to handle the submit button. We want to
* iterate over all the rows, and given that they now have a consistent
* format, parse out the required data and display it.
******/
function submitted() {
console.log("submitted");
$(".container").children("div").each(function() {
var title = $(this).find(".line-title").val();
var firstNum = $(this).find(".first-number-el input").val();
var secondNum = $(this).find(".second-number-el input").val();
console.log(title + ", " + firstNum + ", " + secondNum);
})
}
</script>
<style>
.line-title {
width: 259px;
margin: 0px;
height: 15px;
clear: left;
}
.line-number {
width: 45px;
}
.container {
margin: 10px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<fieldset style=" margin: 0 0 5px 0;">
<!--<div>enter amount of text + number boxes:
<input id="amount" step="1" style=" width: 45px;" type="number" value="1">
</div>-->
<div class="container">
</div>
<button class="add-row-btn">
Add row
</button>
<button class="remove-row-btn">
Remove row
</button>
<input class="button" id="submitBtn" style="margin-left: 85%;" type="button" value="Submit">
</fieldset>
</form>
At the moment the code add new rows when the add row button is clicked. I want to add a similar function to the button 'remove row'. If it were clicked I want the last row to be removed, without affecting the content in the other textboxes. I have tried this, but it did not work:
$(".remove-row-btn").on("click", function(evt) {
evt.preventDefault();
evt.stopPropagation();
$(".container").remove(createNewRow());
})
How can I do this?
Thanks.
You could index the last element and remove it.
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script>
$(function() {
$("#submitBtn").on("click", submitted);
// Created an 'add new row' button, which non-destructively adds a row to the container.
$(".add-row-btn").on("click", function(evt) {
evt.preventDefault();
evt.stopPropagation();
$(".container").append(createNewRow());
})
$(".remove-row-btn").on("click", function(evt) {
evt.preventDefault();
evt.stopPropagation();
$(".container div").eq($(".container div").length - 1).remove();
})
// When the user chooses a different number, completely reset all the rows?
$('#amount').on('change', function() {
// Save a reference to the row container.
var containerEl = $(".container");
// wipe out completely the contents of the container.
containerEl.empty();
// get the number of rows to be created.
var startingNumberOfLines = parseInt($("#amount").val());
// loop the number of times requested, and append a new row each time.
// createNewRow() is defined below.
for (var i = 0; i < startingNumberOfLines; i++) {
$(".container").append(createNewRow());
}
});
// Start with an initial value.
$(".add-row-btn").trigger("click");
})
/*****
* createNewRow() -- function to create a new row, composed of a text input,
* and two labels containing number inputs.
*****/
var createNewRow = function() {
/****
* first, we'll define all the elements that will be placed
* in this row -- the text input, the labels and the inputs.
****/
var lineTitleEl = $("<input>").attr("placeholder", "enter text here")
.addClass("line-title");
var labelEl = $("<label>");
var inputEl = $("<input>").attr("step", "0.05").attr("type", "number")
.addClass("line-number");
// The firstNumberEl is a label containing an input. I can simply
// clone my label el, and input el, and use them. Don't need to,
// but i CAN.
var firstNumberEl = labelEl.clone();
firstNumberEl.text("number1: ").attr("class", "first-number-el").append(inputEl.clone());
var secondNumberEl = labelEl.clone();
secondNumberEl.text("number2: ").attr("class", "second-number-el").append(inputEl.clone());
// Now create the row, which is a div containing those elements.
var newRowEl = $("<div>").append(lineTitleEl, firstNumberEl, secondNumberEl);
// Simply return that row -- the user can send it to the console or
// can append it wherever they like.
return newRowEl;
}
/******
* submitted() -- function to handle the submit button. We want to
* iterate over all the rows, and given that they now have a consistent
* format, parse out the required data and display it.
******/
function submitted() {
console.log("submitted");
$(".container").children("div").each(function() {
var title = $(this).find(".line-title").val();
var firstNum = $(this).find(".first-number-el input").val();
var secondNum = $(this).find(".second-number-el input").val();
console.log(title + ", " + firstNum + ", " + secondNum);
})
}
</script>
<style>
.line-title {
width: 259px;
margin: 0px;
height: 15px;
clear: left;
}
.line-number {
width: 45px;
}
.container {
margin: 10px;
}
</style>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<form>
<fieldset style=" margin: 0 0 5px 0;">
<!--<div>enter amount of text + number boxes:
<input id="amount" step="1" style=" width: 45px;" type="number" value="1">
</div>-->
<div class="container">
</div>
<button class="add-row-btn">
Add row
</button>
<button class="remove-row-btn">
Remove row
</button>
<input class="button" id="submitBtn" style="margin-left: 85%;" type="button" value="Submit">
</fieldset>
</form>

Javascript small game

Right now I am learning some Javascript but got many problems right now since my skills are low. I need some help with several problems in this code.
I am trying to write a game called "hit the fish". It has a timer, score and onclick.
Onlclick the fish should disappear and 1 point will be added in the score. There is a timer limit of 60 seconds.
Here is the whole code.
<html>
<head>
<title>
Hit the fish!
</title>
<style>
table{
margin-left: auto;
margin-right: auto;
width: 70%;
height: 90%;
background-color:#66ff00;
}
#playground input{
position: inherit;
height: 100px;
width: 100px;
margin-left: 20px;
margin-right: 20px;
margin-bottom: 20px;
}
#input {
height:40px;
}
#area {
background-color:#888;
position:absolute;
left:0px;
right:0px;
top:50px;
bottom:0px;
}
#area button {
width:150px;
height:30px;
position:absolute;
}
.red {
color:red;
}
</style>
<script language="Javascript">
function one () {
document.play.one.value="";
// get the counter element
var score = document.getElementById("score");
// get it's value
var value = parseInt(score.innerHTML);
// increase it
value = value + 1;
// write the new value back
score.innerHTML=value;
}
function two () {
document.play.two.value="";
// get the counter element
var score = document.getElementById("score");
// get it's value
var value = parseInt(score.innerHTML);
// increase it
value = value + 1;
// write the new value back
score.innerHTML=value;
}
function three () {
document.play.three.value="";
// get the counter element
var score = document.getElementById("score");
// get it's value
var value = parseInt(score.innerHTML);
// increase it
value = value + 1;
// write the new value back
score.innerHTML=value;
}
function four () {
document.play.four.value="";
// get the counter element
var score = document.getElementById("score");
// get it's value
var value = parseInt(score.innerHTML);
// increase it
value = value + 1;
// write the new value back
score.innerHTML=value;
}
function five () {
document.play.five.value="";
// get the counter element
var score = document.getElementById("score");
// get it's value
var value = parseInt(score.innerHTML);
// increase it
value = value + 1;
// write the new value back
score.innerHTML=value;
}
function six () {
document.play.six.value="";
// get the counter element
var score = document.getElementById("score");
// get it's value
var value = parseInt(score.innerHTML);
// increase it
value = value + 1;
// write the new value back
score.innerHTML=value;
}
function seven () {
document.play.seven.value="";
// get the counter element
var score = document.getElementById("score");
// get it's value
var value = parseInt(score.innerHTML);
// increase it
value = value + 1;
// write the new value back
score.innerHTML=value;
}
function eight () {
document.play.eight.value="";
// get the counter element
var score = document.getElementById("score");
// get it's value
var value = parseInt(score.innerHTML);
// increase it
value = value + 1;
// write the new value back
score.innerHTML=value;
}
function nine () {
document.play.nine.value="";
// get the counter element
var score = document.getElementById("score");
// get it's value
var value = parseInt(score.innerHTML);
// increase it
value = value + 1;
// write the new value back
score.innerHTML=value;
}
function count()
{
stop();
// get the counter element
var counter = document.getElementById("counter");
// get it's value
var value = parseInt(counter.innerHTML);
// increase it
value = value + 1;
// write the new value back
counter.innerHTML=value;
// limitation
if(value===60){
alert("Time Out!");
clearInterval(countTimer);
document.getElementById("counter").innerHTML="0";
document.getElementById("score").innerHTML="0";
}
}
function start () {
stop();
var countTimer = setInterval("count()",1000);
document.play.four.value=">( °3°)";
document.play.three.value=">( °3°)";
setTimeout("nextone ()");
var score = document.getElementById("score");
}
function score(){
// get the counter element
var score = document.getElementById("score");
// get it's value
var value = parseInt(score.innerHTML);
// increase it
value = value + 1;
// write the new value back
score.innerHTML=value;
}
function nextone () {
document.play.four.value="";
document.play.five.value=">( °3°)";
setTimeout("nexttwo ()",400);
}
function nexttwo () {
document.play.three.value="";
setTimeout("nextthree()",400);
}
function nextthree () {
document.play.seven.value=">( °3°)";
document.play.one.value=">( °3°)";
document.play.six.value=">( °3°)";
setTimeout("nextfour ()",700);
}
function nextfour () {
document.play.one.value="";
document.play.six.value="";
document.play.two.value=">( °3°)";
setTimeout("nextfive ()",700);
}
function nextfive () {
document.play.seven.value="";
document.play.two.value="";
document.play.four.value=">( °3°)";
setTimeout("nextsix ()",800);
}
function nextsix () {
document.play.eight.value=">( °3°)";
document.play.two.value=">( °3°)";
setTimeout("nextseven ()",700);
}
function nextseven () {
document.play.eight.value="";
document.play.five.value=">( °3°)";
setTimeout("nexteight ()",400);
}
function nexteight () {
document.play.nine.value=">( °3°)"
document.play.four.value=">( °3°)";
setTimeout("nextnine ()",500);
}
function nextnine () {
document.play.five.value="";
document.play.four.value="";
document.play.one.value=">( °3°)";
setTimeout("nextten ()",200);
}
function nextten () {
document.play.three.value=">( °3°)";
document.play.six.value=">( °3°)";
setTimeout("nexteleven ()",600);
}
function nexteleven () {
document.play.one.value="";
document.play.seven.value=">( °3°)";
setTimeout("nexttwelve ()",500);
}
function nexttwelve () {
document.play.two.value=">( °3°)";
document.play.nine.value=">( °3°)";
setTimeout("nextthirteen ()",700);
}
function nextthirteen () {
document.play.one.value=">( °3°)";
document.play.nine.value="";
document.play.seven.value="";
setTimeout("start ()",600);
}
function stop () {
clearInterval(countTimer);
document.play.one.value="";
document.play.two.value="";
document.play.three.value="";
document.play.four.value="";
document.play.five.value="";
document.play.six.value="";
document.play.seven.value="";
document.play.eight.value="";
document.play.nine.value="";
}
function reset()
{
document.getElementById("counter").innerHTML="0";
document.getElementById("score").innerHTML="0";
}
// get the counter element
var score = document.getElementById("score");
// get it's value
var value = parseInt(score.innerHTML);
// increase it
value = value + 1;
// write the new value back
score.innerHTML=value;
</script>
</head>
<body>
<div id="input">
<button onclick="start()">start</button>
<button onclick="stop()">stop</button>
<button onclick="reset()">reset</button>
<div style="font-size:10em" id="counter">0</div><br>
<p>Your score:</p><div style="font-size:5em" id="score">0</div>
<script>
var countTimer = setInterval('count()',1000);
</script>
</div>
<div id="playground">
<table border=100 cellpadding=0 cellspacing=0>
<tr>
<td>
<form name="play">
<center>
<INPUT TYPE="button" NAME="one" OnClick="one ()" id="one" value=" ">
<INPUT TYPE="button" NAME="two" OnClick="two ()" id="two" value=" ">
<INPUT TYPE="button" NAME="three" OnClick="three ()" id="three" value=" ">
<br>
<INPUT TYPE="button" NAME="four" OnClick="four ()" id="four" value=" ">
<INPUT TYPE="button" NAME="five" OnClick="five ()" id="five" value=" ">
<INPUT TYPE="button" NAME="six" OnClick="six ()" id="six" value=" ">
<br>
<INPUT TYPE="button" NAME="seven" OnClick="seven ()" id="seven" value=" ">
<INPUT TYPE="button" NAME="eight" OnClick="eight ()" id="eight" value=" ">
<INPUT TYPE="button" NAME="nine" OnClick="nine ()" id="ten" value=" ">
<br>
</td>
</tr>
</table>
</div>
</body>
</html>
The problem is the counter goes too fast after 20 - 30, after click the button the fish doesn't disappear and no points are added on score.
In no particular order...
(1) The problems with the counter are due to the way you call it and where you store the countTimer variable. Because you want several functions to be able to access countTimer, you should declare it in a way they can all access it; the simplest way is for it to be a global variable, which you can do just by having
var countTimer;
at the top of the script, and not using var when referring to countTimer elsewhere. You call the function start from the function nextThirteen, and start sets the timer again. What this does is actually set a new timer on top of the old one, which is why the count appears to speed up.
(2) Your html is also not valid which may cause some problems; make sure you close the form and center tags. (You are not supposed to use the center tag any more, anyway).
(3) Your code is in the head but most of it runs straight away, before the page has loaded. So the following line:
var score = document.getElementById("score");
(outside of any of the functions) causes an error because the element score has not been written yet. The simplest way to avoid this is to put your script at the end of the body of the page.
(4) The functions one, two, three need to have different names from the inputs in the form. That is why none of the buttons work.
Some general points as you learn more:
avoid repetition. There's no need for all the one, two, three functions etc. You could use a loop or a single event handler that finds out which button has been pressed.
use your browser's console to check for errors that are being produced. Your code was causing the error object is not a function, and searching for that is how I found out why the buttons were not working.
read about variable scope

Get form fields to hide and populate

I have a 3 fields:
Total amount
Recurring amount
Occurrences
A user will always enter occurrences, but has the choice of entering either total amount or recurring amount.
The equation for this is really simple:
Occurrences * Recurring Amount = Total Amount
I need help making a Javascript function which if the user starts to type in the total amount field, recurring amount becomes disabled. The same is true if they enter recurring amount first. Once the user has input occurrences and either of the amounts, the remaining amount should be calculated and replace the disabled field.
I need the function to be able to allow the user to change any of the numbers, and have the calculation be re-done. Also, if the user totally removes a value from an amount, the other amount field should become active again.
I've never written Javascript code before, only edited. Any help to point me in the right direction is appreciated. Thanks
Not sure why you think disabling fields is a good idea. I think user experience-wise it would be better to allow them to edit any field at any time, adjusting the other fields as needed.
<input id="recurring" onchange="onRecurEdit()"> *
<input id="occurences" onchange="onOccurEdit()"> =
<input id="total" onchange="onTotalEdit()">
<script>
var recur = document.getElementById('recurring');
var total = document.getElementById('total');
var occur = document.getElementById('occurences');
function onTotalEdit() {
recurring.value = total.value / occur.value;
}
function onRecurEdit() {
total.value = occur.value * recur. value;
}
function onOccurEdit() {
total.value = occur.value * recur. value;
}
</script>
Here's partly what you may be looking for: The code uses JQuery
JS code:
$(document).ready(function() {
function roundNumber(num, dec) {
var result = Math.round(num*Math.pow(10,dec))/Math.pow(10,dec);
return result;
}
function calculateTot(evt) {
var o = Number($("#occur").val());
var a = Number($("#recAmt").val());
if(!isNaN(0) && !isNaN(a)) {
var tot = roundNumber(o * a, 2);
$("#totalAmt").val(tot);
}else {
$("#totalAmt").val("0");
}
}
$("#occur").bind("change", calculateTot);
$("#recAmt").bind("change", calculateTot);
});
HTML for the same:
<input type="text" id="occur" /> *
<input type="text" id="recAmt" /> =
<input type="text" id="totalAmt" readonly="readonly" />
This won't be perfect but it should be a decent start:
You can view an interactive demo of this code at http://jsfiddle.net/qzxf7/
You haven't given us your HTML so I'm going to assume you're using something like this:
<form action="" method="POST">
<input type="text" name="occurences" id="occurences" value="" />
<input type="text" name="recurringAmt" id="recurringAmt" value="" />
<input type="text" name="totalAmt" id="totalAmt" value="" />
</form>
If you haven't dealt with Javascript before, I'm going to recommend you use jQuery which is a matter of importing the jQuery script in your HTML <head>.
Using jQuery you could start with code like this which is overly complicated but throws you into how to handle the disabled stuff as well as value updates.
/* On page contents loaded */
function updateForm() {
var occ = $('#occurences');
var occV = parseFloat(occ.val());
occV = occV >= 0 ? occV : 0;
var rec = $('#recurringAmt');
var recV = parseFloat(rec.val());
recV = recV >= 0 ? recV : 0;
var tot = $('#totalAmt');
var totV = parseFloat(tot.val());
totV = totV >= 0 ? totV : 0;
/* If total is disabled */
if (tot.attr("disabled")) {
if (rec.val() == '') { /* if no text in rec */
tot.removeAttr("disabled"); /* Reenable total */
tot.val('');
return;
}
/* Otherwise update total */
tot.val(recV * occV);
return;
}
/* If rec is disabled */
if (rec.attr("disabled")) {
if (tot.val() == '') { /* if no text in total */
rec.removeAttr("disabled"); /* Reenable rec */
rec.val('');
return;
}
/* Otherwise update rec watching for divide by zero error */
rec.val(occV > 0 ? totV / occV : 0);
return;
}
/* Otherwise neither disabled */
if (recV > 0) { /* if rec has a number value */
tot.attr("disabled", true); /* disable total */
tot.val(recV * occV); /* update total */
return;
}
if (totV > 0) { /* if total has a number value */
rec.attr("disabled", true); /* disable rec */
/* Update rec watching for divide by zero error */
rec.val(occV > 0 ? totV / occV : 0);
return;
}
}
$(document).ready(function() {
$('#occurences').keyup(function(){
updateForm();
});
$('#totalAmt').keyup(function(){
updateForm();
});
$('#recurringAmt').keyup(function(){
updateForm();
});
});

Categories