Javascript small game - javascript

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

Related

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

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>

increment in the function name and id javascript

I have number of input types and buttons....every button on click increment the value in the relevant input types. But rather than creating a separate function for every button i want to do it by loop....where loop will increase in the function name and id......
<input type="number" id="s1"> <button onclick="increment_s1();">Add</button>
<input type="number" id="s2"> <button onclick="increment_s2()">Add</button>
<input type="number" id="s3"> <button onclick="increment_s3">Add</button>
here is JavaSc code
<script>
var i = 1;
for (i = 0; i < 5; i++) {
var data = 0;
document.getElementById("s"+i).innerText = data;
function ['increment_'+i]() {
data = data + 1;
document.getElementById("s"+i).placeholder = data;
i++;
}
}
</script>
You can't program the function name. You can set up a parameter in the function to make a difference. The param would be the identifier and you can put the whole input element id there.
After that, if you want to have the id s1, s2, and so on, you should initialize the i to start from 1 to 5 instead of 0 to less than 5.
Another thing is, you need to understand the role of placeholder and value attributes in input element. The placeholder works only when the value is empty and it doesn't count as the form value.
// This is for handling onclick
function increment(id) {
var elem = document.getElementById(id);
elem.value = parseInt(elem.value) + 1;
}
// This is to initialize the 0 values
for (var i = 1; i <= 5; i++) {
var data = 0;
document.getElementById("s"+i).value = data;
}
<input type="number" id="s1"> <button onclick="increment('s1');">Add</button>
<input type="number" id="s2"> <button onclick="increment('s2')">Add</button>
<input type="number" id="s3"> <button onclick="increment('s3')">Add</button>
<input type="number" id="s4"> <button onclick="increment('s4')">Add</button>
<input type="number" id="s5"> <button onclick="increment('s5')">Add</button>
What if you would like to generate whole input and button with loops? You can get them by adding div and use the innerHTML, i.e.
// This is for handling onclick
function increment(id) {
var elem = document.getElementById(id);
elem.value = parseInt(elem.value) + 1;
}
var divElem = document.querySelector('div');
// Set up empty first
divElem.innerHTML = "";
for(var i=1; i<=5; i++) {
// Create elements here
var innerElem = `<input type="number" id="s${i}" value="0"> <button onclick="increment('s${i}')">Add</button>`;
// Push them all into innerHTML
divElem.innerHTML += innerElem;
}
<div></div>
You can try these two workarounds. Perhaps you may need to learn more about basic HTML elements and their attributes also Javascript.

How to assign a prompt value to function parameter

So i have this code:
<div class="wrapper">
<p id="ex"></p>
<script>
function celMessager() {
var celMs = window.prompt("Enter the celsius grades:");
celMs = parseFloat(celMs);
if (celMs == null) {
document.getElementById("ex").innerHTML = "Error.";
}
else {
document.getElementById("ex").innerHTML = celConversor();
}
}
</script>
<button class="button" type="button" onclick="
celMessager();
">
Conversor Celsius.
</button>
</div>
And i want to store the value of the user input (celMs) into the only parameter that celConversor() takes:
function celConversor(celGrades) {
fahGrades = (celGrades * 9/5) + 32;
return fahGrades;
}
So the number that the user enters, become the celsius grades that are going to change into fahrenheit and show it as a paragraph.
How can I do this? tried making the celGrades variable = to celMs and celMs to celGrades, but it always returns "NaN" in the paragraph, even after i added the "parseFloat" line.
You're getting this error celConversor requires a parameter, but you're not passing any parameters to it. Change this line:
document.getElementById("ex").innerHTML = celConversor();
to this:
document.getElementById("ex").innerHTML = celConversor(celMs);

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>

Saving a Value, and adding to it

There are a few ways this can be asked, I'm trying to go with the easiest. Basically, I have two fields... one is to add a number, the other is to subtract. What I want, is when a number is input into either (let's just stick with the add input for now) and have it update at the bottom once the button "+" is pressed. I want that result to stay at the bottom, so when a new value is put into the add box and the button is pressed, it ADDS to the previous total. For the life of me, I can't figure this one out. Once resolved, I'll take care of the subtraction on my own, just need a push in the right direction. The current code is as follows.
<div id="entire">
<div id="content">
<input type="number" id="addInput" placeholder="0">
<button type="button" id="addBtn" onclick="add()">+</button>
<br>
<br>
<input type="number" id="subInput" placeholder="0">
<button type="button" id="subBtn" onclick="sub()">-</button>
<br>
<br>
<div id="totalAmt"></div>
<br>
<input type="button" id="clear" onclick="clearFields()" value="Clear">
<input type="button" id="reset" onclick="reset()" value="Reset">
</div>
</div>
function add() {
var addInput = document.getElementById("addInput").value;
var emptyValue = "";
var total = emptyValue + addInput;
document.getElementById("totalAmt").innerHTML = total;
}
function clearFields() {
document.getElementById("addInput").value = "";
document.getElementById("subInput").value = "";
}
function reset() {
document.getElementById("totalAmt").innerHTML = "";
}
A link to my codepen is below:
http://codepen.io/0ktane/pen/NNdbOq
Your problem is these two lines
var emptyValue = "";
var total = emptyValue + addInput;
when you are concatenating to a string, you get a string back.
Also, you are not even considering the previous value at first place.
Try this, updated pen
function add() {
var addInput = parseInt(document.getElementById("addInput").value); //parse the value to an integer first
var totalAmt = parseInt(document.getElementById("totalAmt").innerHTML); //parse the value to an integer first
totalAmt = isNaN(totalAmt) ? 0 : totalAmt; //if the value is NaN(not a number) reset it to 0
addInput = isNaN(addInput) ? 0 : addInput;//if the value is NaN(not a number) reset it to 0
document.getElementById("totalAmt").innerHTML = totalAmt + addInput ; //output the correct value
}
var total = 0;
function add() {
var addInput = parseInt(document.getElementById("addInput").value);
total = total + addInput;
document.getElementById("totalAmt").innerHTML = total;
}

Categories