How to assign the value of 0 to a variable? - javascript

Javascript function 1:
var count = 0;
function myFunction()
{
count++;
document.getElementById("count").innerHTML=count;
}
Javascript function 2:
function demo() {
var y=document.getElementById("count").innerHTML;
if(y=="0") {
alert("There's nothing to be reset.");
}
else {
var count=0;
alert("Reset.");
// alternative code I used: document.getElementById("count").innerHTML="0";
}
}
HTML code:
Click here
<p>Total:<span id="count">0</span></p>
<button onclick="demo()">reset</button>
Is there a way to reset the variable to 0 in this code?
I've tried to reset the variable count to zero using document.getElementById() and adding =0; to the variable. Neither of these work. For example, if the user was to click the link the count would increase to 1. When they click the reset button it would appear to reset to 0 (unless using `var count=0;). However, if the user were to click the link again the count would be return the value 2, as it could simply continue to increment from the previous time.
I'm sorry if this has already been answered somewhere else, but it's very difficult to search for the terms = and ++.

You made it a local variable by using var
else {
var count=0;
alert("Reset.");
should be
else {
count=0;
alert("Reset.");

Two things:
Get rid of var where you reset the variable. That's giving you a separate local variable with the same name.
Using "count" as a variable name, if it's global, will cause problems if you've also got an element whose id is "count" in the DOM. Use a different variable name or a different id, or make sure that the variable is not global (can't tell from posted code).

The things you need to chnage in the code are:
And make the comparison to
if(parseInt(y) === 0) // You are converting it to integer and doing a strict check
the else construct to
else {
count = 0;
alert('Reset');
}

Related

increasing a number inside of a mouseClicked funtion

I have a code where I draw an object when the mouse is clicked using mouseClicked = function(){} and then I need to have a number to show how many objects have been drawn. the problem is that the number won't increase. what do I do?
Rather than declaring and incrementing a global variable - you could set the count as a HTML 5 data attribute on the button and then on clicking the button, get the data attribute value, increment it and update the display and the new count on the button.
Note that data-attributes are always strings - hence the need for the parseInt() method, though if I was being a purist - I would have put the radix in as well, but that defaults to 10 - so no need in this case.
It is always better to avoid global variable when possible and data attributes offer a very conveniant way of storing local data.
Thanks to #Sven.hig for the skeletn code of the solution - which I then modified to my approach.
var res=document.getElementById("res")
var btn=document.getElementById("btn")
btn.addEventListener("click",()=>{
const newCount = parseInt(btn.getAttribute('data-count'))+1;
res.textContent = newCount;
btn.setAttribute('data-count', newCount)
})
<div id="res"></div>
<button id="btn" data-count="0">Draw</button>
Here is a simple example that will give you an idea about how to increment a counter
var res=document.getElementById("res")
var btn=document.getElementById("btn")
var count=1
btn.addEventListener("click",()=>{
res.textContent=count
count++
})
<div id="res"></div>
<button id="btn">Draw</button>
If the count variable is defined inside the mouseClicked function as the title say, you are recreating it in every mouseClick. In this case, you should define it outter the function with value = 0 and, inside the function, sum 1 to that value. Anyway, like the comments say, it's necessary that you include the code to your question to give a better answer.
this is an easy way to counter the clicks on a html document.
let counter = 0;
document.onclick = () => {
counter++;
console.log(counter);
}

Declaring a global variable and storing a value in it using javascript

I have a form and am trying to track the changes a user made on this form.
The form consist of radio buttons, dropdown and text area which are loaded when
the user selects the first dropdown.
I then decided to count. If the user selects the dropdown again meaning the second time
something has changed.
I want to be able to store result = 1 in a Global variable so that it can be used by another
function on the same page/same view. My application is mvc
How can I store this global variable on the view so that other javascript functions can use it? Is this possible?
var counter = 0;
$("#MyPage")
.on("change", ":input", function () {
counter = counter + 1;
if (counter > 1) {
//This is the first time you are changing.
alert("Something has changed in index page");
var result = 1;
}
});
Simply use result = 1, without var in front
Edit: ssube is correct, use the above method.

javascript: var i is not defined? (clearly defined)

WHAT I WANT TO HAPPEN
So what I want to happen is function partA() to click button [z] every 2 seconds. The button that is being clicked should change, because the script is a looping script, so for instance. The first loop, it would click button 1, then button 2, then button 3, because var z = 1 + i++. Is this possible? z is supposed to equal the number 1, plus the loop number. This should loop as long as variable i is less than 50.
WHAT IS HAPPENING
It works properly, looping and all, if I test the script without variable z. However, without variable z, I have to manually change the number that would equal z, which is painstaking, and annoying.
var z = 1 + i++
for(i=0;i<50;i++) {
setInterval(partA, 2000);
function partA() {
buttons = document.getElementsByTagName('button');
document.getElementsByTagName('button')[z].click();
}
}
Should i++ be defined another way? The error I'm getting when running the script in console is:
Uncaught ReferenceError: i is not defined (...)
at :2:13
at Object.InjectedScript._evaluateOn (:878:140)
at Object.InjectedScript._evaluateAndWrap (:811:34)
at Object.InjectedScript.evaluate (:667:21)
There's a couple of suggestions I could advise with your code so I'll try and address each one individually.
Firstly define your function outside of your loop. If you would like to know the reasons behind this please read: Don't make functions within a loop
Secondly you should really declare i as a variable to set the scope to which it applies. Some good information on this is at: Declaring variables without var keyword
Thirdly when you run your loop you could run the code inside an IIFE. The reason for this is when you run setInterval, by the time it runs i will actually be 3 (or the last number of your loop). This is due to the asynchronous nature of setInterval, and that the reference to i is bound to the function, not the value of i.
Example
for(var i=0;i<3;i++) {
(function(i) {
setInterval(clickButton(i), 2000);
})(i)
}
function clickButton(idx) {
return function() {
buttons = document.getElementsByTagName('button');
document.getElementsByTagName('button')[idx].click();
}
}
JSBin Demo
http://jsbin.com/harigewuze/edit?html,js,output
Why are you trying to define z outside the loop? Just use i.
for (var i = 0; i < 50; i++) {
...
document.getElementsByTagName('button')[i].click();
}
without changing your code too much I would write it like this...
you know its looping 50 times, you know i is incrementing from 0 to 49, use i to change the button name and you don't need z...
for(i=0;i<50;i++) {
setInterval(partA, 2000);
function partA() {
buttons = document.getElementsByTagName('button');
document.getElementsByTagName('button')[i + 1].click();
}
}
1) This is how you want your code to look like :
var z;
for(i=0;i<50;i++) {
z=i;
setInterval(partA, 2000);
}
function partA() {
buttons = document.getElementsByTagName('button');
document.getElementsByTagName('button')[z].click();
}
2) Unfortunately, in javascript you have a problem with this code due to the fact of scopes. My recommendation is to read this link first http://www.mennovanslooten.nl/blog/post/62 and understand how it works.
If you did understand it, then thumb up..you just promoted yourself to a higher level in javascript ;)
3) If you are still having issues, post it on JSFiddle

Every time user clicks on the button I need the next value from the array in Javascript

I'm currently trying to loop an array in a function. This function supposed to be used for a button, which gives every time a different value from the array when its pressed.
var list=['DEFAULT','ADVANCED','DEVELOPMENT'];
Every time user clicks on the button i need the next value from the array. (when its "DEVELOPMENT", next should be "DEFAULT"). Is it possible to do it without using a global variable ?
If you fine with changing array chiliNUT's answer would work (shift/push to implement circular buffer).
Alternatively you can keep current selection and loop that with %. To avoid global variables wrap counter in a function to capture value.
Sample (assuming usage of JQuery, you can find equivalent addEventListener code yourself):
$(function()
{
// outside of click handler to be able to preserve values between clicks
var current = 0;
$("button.next").click(function()
{
alert(list[current]);
current = (current + 1) % list.length;
});
}
<button class="next">Next</button>
something like this. shift pulls off the first element. push sends it to the back.
var list=['DEFAULT','ADVANCED','DEVELOPMENT'];
function nextWord() {
var word=list.shift();
list.push(word);
console.log(word);
return word;
}
nextWord();//DEFAULT
nextWord();//ADVANCED
nextWord();//DEVELOPMENT
nextWord();//DEFAULT
nextWord();//ADVANCED
nextWord();//DEVELOPMENT
//...
<button onclick=nextWord()>Next Word</button>

How to retrieve a conditionally set variable from inside a function?

What can I do to retrieve a conditional variable from inside a function in the webpage being parsed by greasemonkey?
Something like this:
var myglobal = 5;
function myfunc() {
myglobal = myglobal -1;
if (myglobal == -1) {
var this1 = 'Test';
document.getElementById("mybutton").href = this1;
}
}
In this case I would like to read what is in 'this1', either directly or modifying 'myglobal', calling 'myfunc' and somehow getting the value of href from 'mybutton'... any ideas?
You usually can't get a variable value from outside a scope like that, but you may not have to in this case.
"myfunc is a counter, and I want to skip it, otherwise mybutton.href won't be set yet."
Based on the sample code, you might be able to cheat that timer just by using:
unsafeWindow.myglobal = 0;
(In fact, I use this exact technique on one very misguided training site.)
To answer the stated question further, you cannot get dynamic values from within such a scope but the initial state may be enough, as it appears to be for this question.
So you could get myfunc()s code and parse it with regex to obtain the desired value:
var theFunc = unsafeWindow.myfunc.toString ();
var desiredHref = theFunc.match (/var\s+this1\s*=\s*["']([^"']+)["']/);
if (desiredHref.length > 1) {
// Found!
desiredHref = desiredHref[1];
}

Categories

Resources