javascript counter is not increasing counter in each call - javascript

In the javascript code i was expecting that this function should increment the counter each time it is called but the value is remaining same for each time it is called, that is 1.. why is it not incrementing.
<body>
<p>increasing the counter</p>
<button type = "button" onclick="document.getElementById('para').innerHTML = add()">Counter</button>
<p id = "para"></p>
<script>
function add(){
var counter = 0;
return counter = counter + 1;
}
</script>
</body>

Define counter globally(outside the function) or else every time when function is being called, value of counter is set to 0
var counter = 0;
function add() {
return counter = counter + 1; //OR return ++counter;
}
<p>increasing the counter</p>
<button type="button" onclick="document.getElementById('para').innerHTML = add()">Counter</button>
<p id="para"></p>

You need to take your counter variable outside your function definition( i.e. define it as a global variable ), so that it retains its previous value. Otherwise every time you call the function, its value is reset to 0.
<body>
<p>increasing the counter</p>
<button type = "button" onclick="document.getElementById('para').innerHTML = add()">Counter</button>
<p id = "para"></p>
<script>
var counter = 0;
function add(){
return counter = counter + 1;
}
</script>
</body>

counter is set back to 0 in each call.
In this case counter could just be moved outside of the function:
var counter = 0;
function add(){
return counter = counter + 1;
}
<p>increasing the counter</p>
<button type = "button" onclick="document.getElementById('para').innerHTML = add()">Counter</button>
<p id = "para"></p>

Slightly alter program
<html>
<body>
<script>
var counter = 0;
function add() {
return counter = counter + 1;
}
</script>
<p>increasing the counter</p>
<button type="button" onclick="document.getElementById('para').innerHTML = add
()">Counter</button>
<p id="para"></p>
</body>
</html>

Declare counter out of the add() function. Every time add() is invoked the counter is set to ZERO counter = 0 and then it is returned after incrementing by 1 return counter = counter + 1.
var counter = 0;
function add (){
return counter = counter + 1;
}
<p>increasing the counter</p>
<button type = "button" onclick="document.getElementById('para').innerHTML = add()">Counter</button>
<p id = "para"></p>
Second Method, if you want to declare var counter in add() (to avoid polluting global scope ) use JS closure. See following code snippet.
var add = (function (){
var counter = 0;
return function() {return counter = counter + 1;}
})();
<p>increasing the counter</p>
<button type = "button" onclick="document.getElementById('para').innerHTML = add()">Counter</button>
<p id = "para"></p>

Related

my code is about to increment the counter in the browser when we click in the increment button

when we click on the increment button the counter shows in the browser not incrementing.
let countEl = document.getElementById("count-el");
console.log(countEl);
let count = 0;
function increment() {
count = count + 1;
countEl.innertext = count;
}
<h1>people entered</h1>
<h2 id="count-el">0</h2>
<button id="increment-btn" onclick="increment()">INCREMENT</button>
function increment() {
let countEl = document.getElementById("count-el");
let count = countEl.innerHTML;
console.log(count);
count++;
countEl.innerHTML = count;
}
<h1>people entered</h1>
<h2 id="count-el">0</h2>
<button id="increment-btn" onclick="increment()">INCREMENT</button>
Javascript is case-sensitive. in your code you wrote
.innertext = ...
which should have been
.innerText = ...
Also, it is better to attach event click on the button rather on rely on onclick since you can't guarantee if the script file has already been loaded or not.
let countEl = document.getElementById("count-el");
console.log(countEl);
let count = 0;
let button = document.getElementById("increment-btn");
button.addEventListener('click', increment);
function increment() {
count = count + 1;
countEl.innerText = count;
}
<h1>people entered</h1>
<h2 id="count-el">0</h2>
<button id="increment-btn" >INCREMENT</button>

JavaScript-limited click count

I've got a problem with limited click counter using JavaScript. I have tried suggestions below but it seems like my problem might be somewhere else.
HTML/Javascript Button Click Counter
Basically I want to count clicks x times, which is provided from <input type="number"> field. It looks like the script is not recognizing this item in counting function.
Below I'd like to share example code:
function myFunction() {
var count = 0;
var number = document.getElementById("amount").value;
var btn = document.getElementById("clickme");
var disp = document.getElementById("clicked");
btn.onclick = function() {
count++;
disp.innerHTML = count;
}
if (count > number) {
btn.disabled = true;
}
}
<!DOCTYPE html>
<html>
<body>
<input type="number" id="amount">
<p>how many times button should be clicked</p>
<p>Click the button.</p>
<div id="clicked"></div>
<button id="clickme" onclick="myFunction()">Click me</button>
<script>
</script>
</body>
</html>
Just remove the surrounding function and the onclick attribute.
Also, move the value retrieval and the disabled logic inside the listener, and convert the value to a number:
let count = 0;
const btn = document.getElementById("clickme");
const disp = document.getElementById("clicked");
const amount = document.getElementById("amount");
btn.onclick = function () {
count++;
disp.innerHTML = count;
const number = +amount.value;
if (count > number) {
btn.disabled = true;
}
}
<input type="number" id="amount" >
<p>how many times button should be clicked</p>
<p>Click the button.</p>
<div id="clicked"></div>
<button id="clickme">Click me</button>
You can simply your solution using the snippet below.
let count = 0;
const inp = document.getElementById("amount");
const countEl = document.getElementById("clicked");
function myFunction(e) {
if (++count >= Number(inp.value)) e.target.disabled = true;
}
<input type="number" id="amount">
<p>How many times button should be clicked</p>
<p>Click the button.</p>
<button id="clickme" onclick="myFunction(event)">Click me</button>
I would recommend something like this. The limit can be increased or decreased at any time to allow for more or less clicks. Once it reaches 0, the button will stop adding to the count -
const f =
document.forms.myapp
function update (event) {
const limit = Number(f.limit.value)
if (limit <= 0) return
f.limit.value = limit - 1
f.count.value = Number(f.count.value) + 1
}
f.mybutton.addEventListener("click", update)
<form id="myapp">
<input type="number" name="limit" value="10">
<button type="button" name="mybutton">click me</button>
<output name="count">0</output>
</form>
I have managed to count the click events with the limit provided by <input type="number"> field and adding data to the array. Additioanlly, I am trying to decrease dynamically the amount of click events and remove last records from array using another button. Basically I have NAN value when I try to get counter value to decrease it.
It looks like this:
HTML code:
<!DOCTYPE html>
<html>
<body>
<input type="number" id="amount">
<p>how many times button should be clicked</p>
<p> Add question</p> <input type="text" id="question">
<p>Click the button.</p>
<div id="clicked"></div>
<button id="clickme" >add me</button>
<button id="delme">
delete me
</button>
</body>
</html>
JS code:
var count = 0;
var i=0;
const btn = document.getElementById("clickme");
const disp = document.getElementById("clicked");
var amount = document.getElementById("amount");
var question = document.getElementById("question");
var tab;
btn.onclick = function () {
count++;
disp.innerHTML = count;
var number = +amount.value;
tab=new Array(number);
tab[i]=question.value;
console.log(tab[i] + i);
question.value=" ";
i++;
if (count == number) {
btn.disabled = true;
}
}
var delbtn=document.getElementById("delme");
var countdown = parseInt(document.getElementById("clicked"));
delbtn.onclick = function () {
console.log(countdown);
countdown--;
disp.innerHTML = countdown;
if (countdown == 0) {
btn.disabled = true;
}
}

Create Reset button for a counter

I have this counter. It is a counter that uses Javascript Closure. Can you help me with a reset button?
If you can, to this type of "counter" code, not to another...
HTML CODE
<button type="button" onclick="geo()">Count!</button>
<p id="count">0</p>
JAVASCRIPT CODE
<script>
var count= (function () {
var nr = 0;
return function () {nr+= 1; return nr;}
})();
function geo(){
document.getElementById("count").innerHTML = count();
}
</script>
I'm not even sure what you have right now is working.
const addBtn = document.querySelector('#add');
const resetBtn = document.querySelector('#reset');
const pCount = document.querySelector('#count')
let start = 0;
function add(){
start++
pCount.innerHTML = start
}
function reset(){
start = 0;
pCount.innerHTML = start
}
addBtn.addEventListener('click', add)
resetBtn.addEventListener('click', reset)
<button id="add"> Add </button>
<button id="reset" > Reset </button>
<p id="count"></p>
I don't know much about the closure (seems very interesting...) but moving nr variable outside of your function and then call a reset on nr will reset the counter.
var count = (function() {
var nr = 0;
return function(reset = false) {
nr = reset ? 0 : nr + 1
return nr;
}
})();
function geo() {
document.getElementById("count").innerHTML = count();
}
function reset() {
document.getElementById("count").innerHTML = count(true);
}
<button type="button" onclick="geo()">Count!</button>
<button type="button" onclick="reset()">Reset!</button>
<p id="count">0</p>

if condition not running even when the condition satisfies

only the else statement in main.js statement where it reads scores-=1 runs and the if condition doesnt even when the condition satisfies. even after clicking on the right option my scores value doesnt increase by 1 instead it always decreasesby 1 which means it only satisfies the else statement
index.html
<div class="buttons">
<button id="button0"><span id="option0"></span></button>
<button id="button1"><span id="option1"></span></button>
<button id="button2"><span id="option2"></span></button>
<button id="button3"><span id="option3"></span></button>
</div>
main.js
var questions =[{
question:'abcbcb',
options:['a','b','c','d'],
answer:'b'
}, {
question:"capital of india",
options:['delhi','mum','pune','kol'],
answer:'delhi'
}]
var x = Math.floor(Math.random() * (questions.length));
var scores = 0;
function gameplay(){
var quesn = document.getElementById('question');
quesn.innerHTML =questions[x].question;
for(i=0;i<4;i++){
var opt = document.getElementById('option'+i);
opt.innerHTML = questions[x].options[i];
var score = document.getElementById('scores');
score.innerHTML = scores;
}
}
gameplay();
for(i=0;i<4;i++){
var y = document.getElementById('button'+i);
var z = document.getElementById('option'+i);
y.onclick = function(){
if((z.innerHTML) ==(questions[x].answer)){
scores +=1;
}
else{
scores -=1;
}
x=Math.floor(Math.random() * (questions.length));
gameplay();
}
}
For pure Javascript, use the innerHTML property.
For your example, use the following:
var spanVal = document.getElementById("option0").innerHTML;
var x = document.getElementById("option0").innerHTML;
console.log(x)
That is how you can attain the value, ".innerText" would also work.
(btw you labeled this as a question in java, this is javascript. Very different.
Hope this helps.
WORKING SAMPLE
Replace this
for(i=0;i<4;i++){
var y = document.getElementById('button'+i);
var z = document.getElementById('option'+i);
y.onclick = function(){
if((z.innerHTML) ==(questions[x].answer)){
scores +=1;
}
else{
scores -=1;
}
x=Math.floor(Math.random() * (questions.length));
gameplay();
}
}
With this
function answer(ans)
{
var myAnswer = document.getElementById('option'+ans);
if(myAnswer.innerHTML == (questions[x].answer))
{
scores += 1;
}
else{
scores -= 1;
}
x=Math.floor(Math.random() * (questions.length));
gameplay();
console.log(ans);
}
Then this
<p id="question"></p>
<div class="buttons">
<button id="button0"><span id="option0"></span></button>
<button id="button1"><span id="option1"></span></button>
<button id="button2"><span id="option2"></span></button>
<button id="button3"><span id="option3"></span></button>
</div>
<p id = 'scores'></p>
With this
<p id="question"></p>
<div class="buttons">
<button id="button0" onclick ="answer('0')"><span id="option0"></span></button>
<button id="button1" onclick ="answer('1')"><span id="option1"></span></button>
<button id="button2" onclick ="answer('2')"><span id="option2"></span></button>
<button id="button3" onclick ="answer('3')"><span id="option3"></span></button>
</div>
<p id = 'scores'></p>

Javascript not allowing for static variable to be updated each time on click

I am trying to make it where when the user clicks the demo section toggles the flag value each time.
I was under the impression that the static variable was myFunction.flag and it would remain constant throughout the page each time it changes...
<!DOCTYPE html>
<html>
<body>
<p>Search a string for "w3Schools", and display the position of the match:</p>
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var str = "Visit W3Schools!";
var n = str.search(/w3Schools/i);
myFunction.flag = 1;
if(myFunction.flag){
document.getElementById("demo").innerHTML = myFunction.flag;
myFunction.flag = 0;
} else {
document.getElementById("demo").innerHTML = myFunction.flag;
myFunction.flag = 1;
}
}
</script>
</body>
</html>
You are creating a new variable each time a click happen.
Just make it global.
<script>
var flag = 0;
function myFunction() {
var str = "Visit W3Schools!";
var n = str.search(/w3Schools/i);
if(flag){
document.getElementById("demo").innerHTML = myFunction.flag;
flag = 0;
} else {
document.getElementById("demo").innerHTML = myFunction.flag;
flag = 1;
}
}
</script>

Categories

Resources