Display answer of 'Add and Subtract' buttons using javascript - javascript

So I am trying to practice javascript and so I'm trying to do a small javascript code in which a random number is generated whenver the page loads and then the user has the option of subtracting or adding 10 from that number. The user can also input any text in the textfield and the text there will be displayed with the answer. For ex: if the random number generated is 100 and the user choose the 'subtract 10' option and wrote 'Hello' in the text field, the output will be '90Hello'.
I did most of the code, but I can't figure out how to display the answer because it doesn't work for some reason. The random number is shown but the add and subtract buttons are not working. Can someone help with that?
The code till now is:
count = 0;
let y = Math.floor(Math.random() * 100) + 1;
y = document.getElementById("numb").innerHTML;
function subtractTen() {
var t1 = document.getElementById("te");
var n1 = document.getElementById("numb") * 10;
var subtract = Number(n1.value);
var ans = subtract + t1;
var answerSpan = document.getElementById("answer");
answerSpan.innerHTML = out;
}
function addTen() {
var t2 = document.getElementById("te");
var n2 = document.getElementById("numb") / 10;
var add = Number(n2.value);
var ans = add + t2;
var answerSpan = document.getElementById("answer");
answerSpan.innerHTML = out;
}
function reset() {
count = countN * 0;
var res = document.getElementById("numb");
res.innerHTML = count;
}
<html>
<head>
<title></title>
</head>
<body>
<h1> Add Subtract</h1>
<button onClick="subtractTen();" value="sub" /> Subtract 10 </button>
<button onClick="addTen();" value="add" /> Add 10 </button>
<button onClick="reset();" value="res" /> Reset </button>
<br />
<input name="text" id="te" />
<span id="numb" id="answer"></span>
</body>
</html>

//script.js
const container = document.getElementById('answer');
let num = generateRandom(1, 200)
let inputText = '';
function changeText() {
inputText = document.getElementById('te').value
container.innerText = inputText + num;
}
function generateRandom(min, max) {
return Math.floor(Math.random() * (max-min) + min);
}
function subtractTen() {
num -= 10;
container.innerText = inputText+num;
}
function addTen() {
num += 10;
container.innerText = inputText+num;
}
function reset() {
num = generateRandom(1, 200);
container.innerText = num
inputText = '';
document.getElementById('te').value = ''
}
container.innerText = num;
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Document</title>
<script defer src="script.js"></script>
</head>
<body>
<h1> Add Subtract</h1>
<button onClick="subtractTen()" value="sub" /> Subtract 10 </button>
<button onClick="addTen()" value="add" /> Add 10 </button>
<button onClick="reset()" value="res" /> Reset </button>
<br />
<input oninput="changeText()" name="text" id="te" />
<span id="answer"></span>
</body>
</html>

Related

how i am going to clearInterval when i press stop btn?

i am truly new with programing with javaScript so i just start to learn it, it will be good you are going to reply using a simple js code
my code does'nt stop when i press stop i want to clear the interval that i named with myTimer if i didn't put setInterval inside the function it just work directly and if there is any way to make my code more short please mentiot it.
const // my variable
myHour = document.getElementById("hours"),
myMin = document.getElementById("min"),
mySecond = document.getElementById("second"),
myMiliSecond = document.getElementById("dsecond"),
startchrono = document.getElementById("start"),
getLap = document.getElementById("lap"),
stopchrono = document.getElementById("stop"),
resetchrono = document.getElementById("reset"),
result = document.getElementById("result");
let // variable
milisecond = 0,
second = 0,
minute = 0,
hour = 0,
chronoRun = false,
round = 0;
function decoration(item) // this function is for add 0 if second or minute less than 10
{
if (String(item).length < 2) {
item = "0" + item;
}
return item;
}
function lapset() // function that create a new row in the table to save rounds
{
round++;
let // decoration add 0 if number under 10
ds = decoration(milisecond),
s = decoration(second),
m = decoration(minute),
h = decoration(hour);
if (round <= 10) {
const // insert the row in table
tr = result.insertRow(-1);
tr.insertCell(0).innerHTML = round;
tr.insertCell(-1).innerHTML = h + ":" + m + ":" + s + ":" + ds;
} else if (round <= 11) {
tr = result.insertRow(-1);
tr.insertCell(-0).innerHTML = "-";
tr.insertCell(-1).innerHTML = "you can't add any more laps";
getLap.setAttribute("disabled", "true");
}
}
function chrono() //chrono start
{
// chrono
milisecond++;
// make sure that minute, second have to be less than 60
if (milisecond > 10) {
milisecond = 0;
second++;
}
if (second > 59) {
second = 0;
minute++;
}
if (minute > 59) {
minute = 0;
hour++;
}
let // decoration add 0 if number under 10
ds = decoration(milisecond),
s = decoration(second),
m = decoration(minute),
h = decoration(hour);
myMiliSecond.innerHTML = ds;
mySecond.innerHTML = s;
myMin.innerHTML = m;
myHour.innerHTML = h;
startchrono.setAttribute("disabled", "true");
}
// function chronoStarts() {}
const myTimer = () => {
setInterval(chrono, 100);
};
const test = () => {
return clearInterval(myTimer);
};
startchrono.addEventListener("click", myTimer);
getLap.addEventListener("click", lapset);
stopchrono.addEventListener("click", test);
<!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 id="chrono">
<div id="timer">
<span id="hours" class="time">00</span>
<span class="sep">:</span>
<span id="min" class="time">00</span>
<span class="sep">:</span>
<span id="second" class="time">00</span>
<span class="sep">:</span>
<span id="dsecond" class="time">00</span>
</div>
<div id="btnarea">
<button id="start" class="btnevent">start</button>
<button id="lap" class="btnevent">lap</button>
<button id="stop" class="btnevent">stop</button>
<button id="reset" class="btnevent">reset</button>
</div>
<table id="result">
<caption>saved lap</caption>
<tbody>
<tr>
<th class="round">round</th>
<th class="laptime">time</th>
</tr>
</tbody>
</table>
</div>
<script src="newpagescript.js"></script>
</body>
</html>
and that is my html code i think every is ok with my code but if there any issue i am looking for adives
You need to get the return value of the setInterval function and then pass that value as a parameter in the clearInterval function. For example, see below:
`// function chronoStarts() {}
let intervalId = 0;
const myTimer = () => {intervalId = setInterval(chrono, 100);};
const test = () => {
clearInterval(intervalId);
};
startchrono.addEventListener("click", myTimer);
getLap.addEventListener("click", lapset);
stopchrono.addEventListener("click", test);`

How to make a modified counter animation in JavaScript?

I need to create a web page that shows two buttons: "Start" and "Stop". When "Start" is clicked, I need to display an equation every second. For example:
Suppose that the starting number is 100, then in the animation, the web page will first display:
100 + 1 = 101
And then every second after that, it should display:
100 + 2 = 102;
100 + 3 = 103;
100 + 4 = 104;
and so on...every 1 second.
I have been able to create the counter animation, however, I am stuck as to how to progress after this.
Here is my code so far
<html>
<head>
<script>
var counter = 100;
var counterSchedule;
function startCounterAnimation(){
counterSchedule = setInterval(showCounter, 1000);
}
function showCounter(){
counter = counter + 1;
var counterSpan = document.getElementById("counter");
counterSpan.innerHTML = counter;
}
function stopCounterAnimation(){
clearInterval(counterSchedule);
}
</script>
</head>
<body>
<button onClick="startCounterAnimation()">Start Animation</button>
<button onClick="stopCounterAnimation()">Stop Animation</button>
<br /><br />
<span id="counter"></span>
</body>
</html>
Any help would be greatly appreciated!
Try out with the code below. Is that what you're looking for?
var counter = 100;
var counterSchedule;
let i = 1;
function startCounterAnimation(){
counterSchedule = setInterval(showCounter, 1000);
}
function showCounter(){
counter = counter + 1;
var counterSpan = document.getElementById("counter");
counterSpan.innerHTML = `100 + ${i} = ${counter}`;
i++;
}
function stopCounterAnimation(){
clearInterval(counterSchedule);
}
<html>
<head>
</head>
<body>
<button onClick="startCounterAnimation()">Start Animation</button>
<button onClick="stopCounterAnimation()">Stop Animation</button>
<br /><br />
<span id="counter"></span>
</body>
</html>

Stuck with javascript (beginner)

I have just started learning javascript and i am stuck with my first lab. I have the HTML part working but none of the javascript is working. At first I thought it did not link the javascript code to the HTML code correctly but now i think there is issues with the onload and oninput part. But have no idea why. If someone can help would be appreciated.
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Lab 11 suits</title>
<script src="Lab1.js"></script>
</head>
<body>
<heading>
<h1>
HTML 5 Test Page
</h1>
</heading>
<p id="test"></p>
<button id="button">Press Me</button>
<p/>
Colours:<select id="list">
<option>Red</option>
<option>Green</option>
<option>Blue</option>
</select>
<p/>
Your Birthday:<input type="date" id="dod"/>
A Number: <input type="range" id="range" min="1" max="10" value="1">
<span id="value">1</span>
</body>
</html>
window.onload = function() {
var para = document.getElementById("heading");
para.innerText = "A short exercise on creating dynamic web content.";
var button = document.getElementById("button");
button.onclick = function () {
alert("Ive been clicked");
};
var list = document.getElementById("list");
list.onchange = function () {
var item = list.options[list.selectedIndex].text;
changeColour(item);
};
var dob = document.getElementById("dob");
dob.oninput = function () {
alert("Your birth date is:" + dob.value);
};
var range = document.getElementById("range");
var value = document.getElementById("value");
range.onchange = function () {
value.innerText = range.value;
};
function changeColour(colour) {
var c = 0;
switch (colour) {
case "Red":
c = "#f00";
break;
case "Green":
c = "#0f0";
break;
case "Blue":
c = "#00f";
break;
}
document.bgColor = c;
};
function daysOld(dob) {
var msPerDay = 1000 * 60 * 60 * 24,
now = new Date(),
diff = now - dob;
return diff / msPerDay;
};
};
I have made a couple of edits:
Missing id on the heading element
typo on the id="dob" you had id="dod"
window.onload = function() {
/******* EDIT 1 ********/
// the heading element has no ID, so you need to add one, or use `querySelector` instead.
//var para = document.getElementById("heading");
var para = document.querySelector("heading");
/***********************/
para.innerText = "A short exercise on creating dynamic web content.";
var button = document.getElementById("button");
button.onclick = function () {
alert("Ive been clicked");
};
var list = document.getElementById("list");
list.onchange = function () {
var item = list.options[list.selectedIndex].text;
changeColour(item);
};
var dob = document.getElementById("dob");
dob.oninput = function () {
alert("Your birth date is:" + dob.value);
};
var range = document.getElementById("range");
var value = document.getElementById("value");
range.onchange = function () {
value.innerText = range.value;
};
function changeColour(colour) {
var c = 0;
switch (colour) {
case "Red":
c = "#f00";
break;
case "Green":
c = "#0f0";
break;
case "Blue":
c = "#00f";
break;
}
document.bgColor = c;
};
function daysOld(dob) {
var msPerDay = 1000 * 60 * 60 * 24,
now = new Date(),
diff = now - dob;
return diff / msPerDay;
};
};
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Lab 11 suits</title>
<script src="Lab1.js"></script>
</head>
<body>
<heading>
<h1>
HTML 5 Test Page
</h1>
</heading>
<p id="test"></p>
<button id="button">Press Me</button>
<p/>
Colours:<select id="list">
<option>Red</option>
<option>Green</option>
<option>Blue</option>
</select>
<p/>
<!-- EDIT 2 -->
<!-- You had a typo on the id of your input 'dod' -> 'dob' -->
<!-- Your Birthday:<input type="date" id="dod"/> -->
Your Birthday:<input type="date" id="dob"/>
<!-- End EDIT -->
A Number: <input type="range" id="range" min="1" max="10" value="1">
<span id="value">1</span>
</body>
</html>

How to replace an appendChild instead of it adding to the previous appendChild?

I created a simple simple javascript program where when I click two buttons that I generate random numbers and the third button allows me to sum the two numbers up and then I can reset.
Codepen with update
<html lang="en">
<head>
<title>createTextNode example</title>
</head>
<body>
<button onclick="addTextNode1('Hi!');">N. 1</button>
<button onclick="addTextNode('NO! ');">N. 2</button>
<button onclick="test2('NO!.. ');">A! </button>
<button onclick="myFunction3()">Reset page</button>
<hr />
<p id="p2">1: </p>
<p id="p1">2: </p>
<p id="p3">T: </p>
</body>
</html>
function addTextNode(simple1) {
text1 = Math.floor((Math.random() * 100) + 1);
var newtext = document.createTextNode(text1+" "),
p1 = document.getElementById("p1");
p1.appendChild(newtext);
}
function addTextNode1(simple2) {
text2 = Math.floor((Math.random() * 100) + 1);
var newtext = document.createTextNode(text2+" "),
p2 = document.getElementById("p2");
p2.appendChild(newtext);
}
function myFunction3() {
window.location.reload(true);
}
function test2() {
text5 = text1 + text2;
var newtext5 = document.createTextNode(text5),
p3 = document.getElementById("p3");
p3.appendChild(newtext5);
}
My question is how would I be able to replace the number that was newly displayed by the button by the appendChild method, so that when I click the button again the previous number gets replaced.
Thanks! Much appreciate!
Here an example for the second number.Same for the other:
function addTextNode(simple1) {
text1 = Math.floor((Math.random() * 100) + 1);
var newtext = document.createTextNode(text1+" "),
p1 = document.getElementById("p1");
var p1Txt=p1.innerHTML;
var a=p1Txt.length;
if(a>=3){
p1.innerHTML='2: ';
p1.appendChild(newtext);
}else{
p1.appendChild(newtext);
}
Great to hear that you are programming!
Nice post about onclick attribute attaching events
If you need some functionality more than once,wrap this in a function.(random integer).It makes code cleaner and you dont need to repeat yourself.
Check this out.I bet this example is far from perfect but still give some insights
// You can use some library like "Lodash" to use such functions.
// returns random integer in span <min:max>
function randomInteger(min = 1, max = 100){
// in case that there are wrong values
if(min >= max){throw new Error(`Hey i cant get random integer in range min:${min} to max:${max}`)}
return Math.round((Math.random() * (max-min))+min)
}
// buttons
var number1GeneratorButton = document.getElementById('number1-generator'),
number2GeneratorButton = document.getElementById('number2-generator'),
calculateSumButton = document.getElementById('sum-button'),
resetPageButton = document.getElementById('reset-page');
// outputs
var number1Output = document.getElementById('number1'),
number2Output = document.getElementById('number2'),
sumOutput = document.getElementById('sum');
// add event listeners to the buttons
number1GeneratorButton.addEventListener('click', function(){
number1Output.innerHTML = randomInteger();
})
number2GeneratorButton.addEventListener('click', function(){
number2Output.innerHTML = randomInteger();
})
calculateSumButton.addEventListener('click', function(){
var sum = parseInt(number1Output.innerHTML) + parseInt(number2Output.innerHTML);
sumOutput.innerHTML = sum;
})
resetPageButton.addEventListener('click', reloadWindow)
function reloadWindow() {
window.location.reload(true);
}
// function addTextNode2(simple3) {
// text3 = text2 + text1
// var newtext1 = document.createTextNode(text3),
// p3 = document.getElementById("p3");
// p3.appendChild(newtext1);
// }
// function addTextNode4() {
// if (text1 > text2){
// text3 = text1 - text2;
// var newtext4 = document.createTextNode(text3),
// p3 = document.getElementById("p3");}
// else if(text2 > text1){
// text3 = text2 - text1;");}
// var newtext4 = document.createTextNode(text3),
// p3 = document.getElementById("p3
// p3.appendChild(newtext4);
// }
// function test(sampleplace1){
// if(text1 > text2){
// q = text1 - text2;
// var storm = document.createTextNode(q).value,
// p1 = document.getElementById("p1");}
// else if(text2 > text1){
// z = text2 - text1;
// var storm = document.createTextNode(z).value,
// p1 = document.getElementById("p1");
// }
// p1.appendChild(storm);
// }
<html lang="en">
<head>
<title>createTextNode example</title>
</head>
<body>
<button id="number1-generator">Number1Generator</button>
<button id="number2-generator">Number2Generator</button>
<button id="sum-button">CalculateSum</button>
<button id="reset-page">Reset page</button>
<hr />
<p>Number1: <span class="numbers" id="number1"></span></p>
<p>Number2: <span class="numbers" id="number2"></span></p>
<p>Sum: <span id="sum"></span></p>
</body>
</html>

put in multiply or divide in input field to perform either multiply or divide on the other 2 input fields

Hey guys im trying to create a function that takes 3 arguments. The first argument is supposed to be "MULTIPLY" or "DIVIDE" in an input field, then followed by two numbers which are also in separate input fields, that should be either multipled or divided according based on the first argument. I cant figure out exactly how i'm supposed to write this down in code.
this is my code so far;
<!DOCTYPE html>
<html>
<head>
<script src="ovning3-3.js"></script>
<meta charset="UTF-8">
<title></title>
</head>
<body>
<h1></h1>
<p>
</p>
<input id="first" type="text">
<input id="second" type="text">
<input id="third" type="text">
<input type="button" value="Multiply" onclick="multiply()">
<input type="button" value="Divide" onclick="divide()">
<input type="button" value="Multiply and Divide" onclick="multiplyAndDivide()">
</body>
</html>
and the java script;
function multiply() {
var x = document.getElementById("first").value;
var y = document.getElementById("second").value;
var z = document.getElementById("third").value;
var result = (x * y) * z
alert(result)
}
function divide() {
var x = document.getElementById("first").value;
var y = document.getElementById("second").value;
var z = document.getElementById("third").value;
var result = (x / y) / z
alert(result)
}
function multiplyAndDivide() {
multiply();
divide();
}
Any help out there?
You can use only one function
function multiplyOrDivide(todo){
var x = document.getElementById("first").value;
var y = document.getElementById("second").value;
var z = document.getElementById("third").value;
if(todo==0){
alert(Number(x*y*z));
}
else{
if(y!=0 || z!=0){
alert(Number(x/y)/z);
}
}
}
In onclick you can pass options as multiplyOrDivide(1)
See if this is what you want
<!DOCTYPE html>
<html>
<head>
<script>
function calculate() {
var x = document.getElementById("first").value;
var y = document.getElementById("second").value;
var d = document.getElementById("decision").value;
if (d=="*")
result = x*y;
else if(d=="/")
result = x/y;
alert(result)}
</script>
<title></title>
</head>
<body>
<h1></h1>
<select id="decision">
<option value="*">Multiply</option>
<option value="/">Divide</option>
</select><br>
<input id="first" type="text">
<input id="second" type="text"><br>
<input type="button" value="Calculate" onclick="calculate()">
</body>
</html>
Let me know if you need any further explaination
You can use select menu to choice which operation you want to perform. To use js functionality, you can take a look this:
function calculate() {
var selected_operation = document.getElementById("operation");
var operation = selected_operation.options[selected_operation.selectedIndex].value;
if (operation == 'multiply')
multiply(operation);
else if (operation == 'divide')
divide();
else if (operation == 'mulitiply_division')
multiplyAndDivide();
}
function multiply() {
var x = document.getElementById("first").value;
var y = document.getElementById("second").value;
var z = document.getElementById("third").value;
var result = (x * y) * z
alert(result);
}
function divide() {
var x = document.getElementById("first").value;
var y = document.getElementById("second").value;
var z = document.getElementById("third").value;
var result = (x / y) / z
alert(result);
}
function multiplyAndDivide() {
multiply();
divide();
}
To see the whole scenario, please visit DEMO
function mul()
{
var a = document.getElementById("v1").value;
var b = document.getElementById("v2").value;
document.getElementById("ans").innerHTML = "Multiplication is: " + a * b;
}
function div()
{
var a = document.getElementById("v1").value;
var b = document.getElementById("v2").value;
document.getElementById("ans").innerHTML = "Division is: " + a / b;
}
<!DOCTYPE html>
<html>
<head>
</head>
<style>
body{
padding-left: 80px;
}
</style>
<body>
<p id="ans"></p>
<input type="text" placeholder="Value 1" id="v1"><br><br>
<input type="text" placeholder="Value 2" id="v2"><br><br>
<input type="button" onclick="mul()" id="mul" value="Multiplication">
<input type="button" id="div" onclick="div()" value="Division">
</body>
</html>
Explanation:
document.getElementById(id).value: The value property sets or returns the value of the value attribute of a text field.
document.getElementById("result").innerHTM : The innerHTML property sets or returns the HTML content (inner HTML) of an element.

Categories