i try to do these code and expecting it for increase by 1 everytime i click on the button but it returns me NaN instead.
im really new to javascript. really hope someone could help me!
thanks in advance.
function add(){
var sum = parseInt(1);
var adding = adding + sum;
document.getElementById("amt1").innerText = adding;
}
I see, here you've asked two problems:
Why adding is NaN
At line #2, you haven't initialized variable adding, hence in RHS adding is undefined.
Therefore, the RHS block adding + sum; is evaluated as undefined + 1, which evaluates to NaN
How to use onClick()
W3School's tutorial on onClick()
Here is your code in working state (HTML + JavaScript):
var adding = 0; // initialization. This is the step, that your code was missing
function add() {
var sum = parseInt(1);
adding = adding + sum;
document.getElementById("amt1").innerText = adding;
}
<h1>The onclick Event</h1>
<button onclick="add()">Click me</button>
<p id="amt1"></p>
You could take a closure over the sum and take the returned function for adding to the value.
var add = function(sum) {
return function () {
document.getElementById("amt1").innerHTML = ++sum;
};
}(0);
<span id="amt1">0</span> <button onclick="add()">add</button>
You're making the assignment in the local scope of the function, so every time the function executes, it's going to assign the value 1 to the 'sum' variable. Next, you're creating the variable 'adding' by trying to assign the value of adding, which doesn't exist yet.
It seems like the goal of your function is to just increment the value of 'amt1' by one.
function add(elId){
let currentAmt = document.getElementById(elId).innerText;
currentAmt = parseInt(currentAmt) + 1;
document.getElementById(elId).innerText = currentAmt;
}
By passing in the element ID, your function can now be applied to any element. It parses the integer from its current inner text, adds 1, then sets the new amount to the inner text of the element.
you might need to have a look on this post- Increment value each time when you run function
about how to increment, the idea is keep the variable outside the function as in you case,
you dont need parseInt as its used for parsing integers from a string.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/parseInt
you need to keep the sum variable outside function. following is the general function to add
var n = 0;
function add(value){
n += value;
return n;
}
try it
document.getElementById("amt1").addEventListener("click", displayDate);
function displayDate() {
var node = document.getElementById('amt1');
document.getElementById("amt1").innerHTML = parseInt(node.textContent)+1;
}
<button id="amt1">1</button>
You're using an undefined variable adding to make your calculation that's why you get a NaN as a result :
var adding = adding + sum : the variable adding isn't yet initialized so it's value equals to undefined which give us var adding = undefined + sum = NaN. See next example :
var sum = parseInt(1);
console.log('typeof "adding" before initialization is ' + typeof adding + ' and it equals "' + adding + '"');
var adding = adding + sum;
console.log('typeof "adding" after initialization is ' + typeof adding + ' and it equals "' + adding + '"');
BTW, you don't need parseInt in order to put manually a number, sum = parseInt(1) is the same as sum = 1 but the later is faster.
And now here's how to accomplish your task :
/**
* btn: the button to be clicked to increment the counting.
* counterTxt: the "p#counter" element that prints the counting.
* counter: keeps track of the number of the clicks made.
**/
const btn = document.getElementById('btn'),
counterTxt = document.getElementById('counter');
let counter = 0; /** holds the number of clicks **/
/** click event handler for the "button" **/
btn.addEventListener('click', () => counterTxt.textContent = ++counter); /** update the "p#counter" text and increment the counter **/
<button id="btn">click to increment</button>
<p id="counter">0</p>
Related
I have these set of 11 numbers that increase per second, but I want each increment or the current set of numbers to write on a new line. E.g;
20220215155
20220215156
20220215157 etc...
I tried adding the n tag buh it returned an error.
var i = 20220215155
function increment() {
i+, + </n>;
document.getElementById('test').innerHTML = i
}
('increment()', 1000);
Please I really need help as I have been trying to get this for so long.
Your code is not valid JS
Here is something that does work - I am using setInterval here
var i = 20220215155
function increment() {
i++; // increment
document.getElementById('test').innerHTML += i + "<br/>"; // add it with a breakline
}
setInterval(increment, 1000);
<div id="test"></div>
You can use a template literal for the string too
`${i}<br/>`
You can use setTimeout to call the function after a set time while also increasing the number you initially pass into the function.
// Cache the element
const test = document.querySelector('#test');
let n = 20220215155;
// `increment` accepts `n` as an argument
function increment(n) {
// Add a new HTML string to the element
test.innerHTML += `${n}</br>`;
// Call the function again with an new `n`
setTimeout(increment, 1000, ++n);
}
increment(n);
<div id="test"></div>
Additional documentation
Template/string literals
I'm working on a basic P5 program that requires up to ten input boxes.
So I need to first create the button instances, using e.g.
factor1Input = createInput(""); // create DOM element for input field
factor1Input.position(leftMargin, topMargin + 50); // place button on screen
factor1Input.changed(this.factor1update); // call function when value changes
factor1Button = createButton('Update Factor'); // create DOM element for button
factor1Button.position(100, 100); // position button
Then toggle their visibility using e.g.
factor1Input.show(); // toggle display on
factor1Button.show();
factor1Input.hide(); // or toggle it off
factor1Button.hide();
But because I'll have up to 10, this will require a ton of repetitive code.
So I want to create a loop that goes something like (e.g. just for the show function);
for (let i = 1; i < factorCount; i++){
let fci = "factor" + i + "Input";
let fcb = "factor" + i + "Button";
fci.show();
fcb.show();
}
But I'm getting the following error:
Uncaught TypeError: fci.show is not a function
Which suggests some kind of type mismatch, i.e. I can't seem to just compile a string, and have this recognized as the JavaScript function.
Any suggestions?
fci will be a string so the String class will not have a method show, You will get an exception. Instead
You can write in this way
var factorObject = {
factor1Input:createInput("")
}
factorObject['factor1Input'].position(leftMargin, topMargin + 50);
For show
factorObject['factor1Input'].show();
Here in the loop
for (let i = 1; i < factorCount; i++){
let fci = "factor" + i + "Input";
factorObject[fci].show();
}
The reason why your code doesn't work is because you create a string and try to call it like a variable with the same name
let fci = "factor" + i + "Input";
fci.show(); // fci is just a string 'factor1Input', has nothing in common with factor1Input variable
You should use arrays Arrays and instead of keeping input number (e.g. index) inside a name, let it be the index of an item in the array
const factorCount = 10
const inputs = []
const buttons = []
// example of creating inputs and buttons in a loop, you can create them manually if you want,
// but don't forget to .push them to respective array
for (let i = 1; i < factorCount; i++){
const input = createInput("");
input.position(leftMargin, topMargin + 50 * i); // using index to calculate top margin
input.changed((value) => this.factorUpdate(i, value)); // notice the change here
inputs.push(input)
const button = createButton('Update Factor');
button.position(100, 100 + 50 * i); // also using index to calculate top margin
buttons.push(button)
}
function showInput(index) {
inputs[index].show()
buttons[index].show()
}
function hideInput(index) {
inputs[index].hide()
buttons[index].hide()
}
showInput(3) // shows 3rd input and button
hideInput(4) // hides 4th input and button
Notice also how I changed your this.factor1update method call. The same way you don't want to have 10 separate variables for 10 elements, you don't want to have 10 methods to handle changes on those 10 elements (what if there was 10000 elements?). Instead, create one method factorUpdate that will receive item index and the value that was changed and use that to handle the input change
added:
for (let i = 0; i < factorCount; i++){ // changed 1 to 0 here, it was a typo
const input = createInput("");
input.position(leftMargin, topMargin + 50 * i);
input.changed(() => factorUpdate(i)); // we call factorUpdate with index of an element
inputs.push(input)
const button = createButton('Update Factor');
button.position(185, topMargin + 50 * i);
buttons.push(button)
}
function factorUpdate(i, event){
// argument i is now an index of unfocused input
console.log("input index: " + i + ", value: " + inputs[i].value());
}
Note also how input.changed() works: you edit the input, then you click somewhere else on the page to unfocus it, and that's when this event is triggered. With that in mind, buttons here don't actually do anything as there are no click listeners assigned to them
In the following code, the user is able to create variables utilizing the window object via an input type text element. I've written a function that console logs the name of the variable followed by the value of 0 in which the variable is initialized. This only occurs when the following key string literal, "-nr " precedes the desired name for the created variable.
The goal of this exercise is to increment any created variable value by 1 when the variable name is reentered into the input element. My attempt at doing so is by first writing the first function, varCreate to declare and initialize variables to 0, push them into an array, and console log the variable name followed by its value. The next function which I have a problem with (varPlus) is meant to add 1 to the value of each value when a particular name is entered into the input element however, it adds a few more than 1 even when I utilize a for loop to evaluate if the string literal value of the input element value property is equivalent to each element of the array varArray.
const _in = document.getElementById('in');
var varArray = [];
function varCreate(e) {
let _key = e.key;
if(_key === "Enter") {
if(_in.value.substring(0, 4) == "-nr ") {
window[_in.value.substring(4).replace(/\s/g, "_")] = 0;
varArray.push(_in.value.substring(4).replace(/\s/g, "_"));
console.log("var: " + varArray[varArray.length - 1] + "\nvalue: " + window[varArray[varArray.length - 1]]);
_in.value = "";
}
}
}
function varPlus(e1) {
let _key1 = e1.key;
if(_key1 === "Enter") {
checker = new RegExp(_in.value.replace(/\s/g, "_"), "gi");
for(var i = 0; i < varArray.length; i++) {
if(checker.test(varArray[i])) {
window[varArray[i]] += 1;
console.log("var: " + varArray[i] + "\nvalue: " + window[varArray[i]]);
}
}
delete window["checker"];
}
}
_in.addEventListener('keydown', varCreate);
_in.addEventListener('keydown', varPlus);
<input id='in' type='text' />
The end result when attempting to utilize varPlus is that it'll console log all variable names and values which somehow increment in value when it should only be console logging only the variable name which I'm trying to access via user input followed by its value. I would greatly appreciate it if anyone can shed some light on how I'm encountering these errors.
First of all it is really helpful if you try and make your code executable :)
Now for the user generated variables you could do something like this:
// DOM Elements
const input_variable = document.getElementById("input_variable");
const button_createVariable = document.getElementById("button_createVariable");
// Variables
let userVariables = {};
// Event listeners
window.addEventListener("keyup", event => {if(event.key == "Enter") parseVariable()});
button_createVariable.addEventListener("click", parseVariable);
function parseVariable() {
// Get the variable name and remove all spaces
let variableName = input_variable.value.substring(0, input_variable.value.indexOf("=")).replace(/\s+/g, '');
// Get the variable value and remove all spaces
let variableValue = input_variable.value.substring(input_variable.value.indexOf("=") + 1, input_variable.value.length).replace(/\s+/g, '');
// Add the variable to the object
userVariables[variableName] = variableValue;
// Clear the input
input_variable.value = "";
// Log the object into the console
console.log(userVariables);
}
<input id='input_variable' type='text'/><button id="button_createVariable">Create</button>
WARNING You of course still need to verify the user input. At this state it will accept everything as input. But now you can loop through the object and count up (or whatever) if already exists.
Oh yes btw, the syntax is simply: <name> = <value> eg. foo = 10.. unimportant detail :P
I have a hopefully pretty easy problem. I'm trying to create a JS function on my app where there's a number in HTML and every time it is clicked, another number is subtracted from it and the result displays.
(So far this much works.)
Then the action should be repeatable so the number keeps getting smaller.
(This part doesn't work yet.)
Finally, there's a reset button that, when clicked, resets the original number to a random number.
(The random number is found correctly, but when you click to subtract it subtracts from the original number, not from the randomly-chosen replacement number.)
Here's a partially-working JSFiddle
var s = document.getElementById('incrimentOfNumber').innerHTML
var n = document.getElementById('countdownNumber').innerHTML
var n = n - s;
document.getElementById("countdownNumber").onclick = function updateNumber(){
this.innerHTML = n;
}
document.getElementById("resetCountdown").onclick = function resetCountdown(){
var n = Math.floor(Math.random() * 500) + 200;
document.getElementById("countdownNumber").innerHTML = n;
}
<h3>Count down from the number you see in incriments of <span class="incrimentOfNumber" id="incrimentOfNumber">7</span>.
<br />Tap the number to see the correct answer.
<br />Repeat as needed.
</h3>
<div class="countdownNumber">
<h1 id="countdownNumber">284</h1>
</div>
<div class="btn" id="resetCountdown">Reset</div>
Can anyone (1) double check what I've done to make sure I'm not doing things in a stupid way and (2) help me figure out how to get the repeatable action functioning?
The issue is you are calculating value of n only once, it should be calculated on every click thus change you countdown click function to:
document.getElementById("countdownNumber").onclick = function updateNumber(){
var s = document.getElementById('incrimentOfNumber').innerHTML
var n = document.getElementById('countdownNumber').innerHTML
n = n - s;
this.innerHTML = n;
}
Here is a working demo:
https://jsfiddle.net/m3q8fn2x/
If you are still struggling with this ,then consider the fact that when you declare a variable inside an event function its starting value is always the same , when the event is triggered. So consider this fact and declare variables outside the event function's scope.
const togglerBtn = document.getElementById("togglerBtn");
let temp = false;
togglerBtn.addEventListener("click", () => {
// alert();
if (!temp) {
togglerDiv.style.transform = "translateY(48px)";
return (temp = true);
} else if (temp) {
togglerDiv.style.transform = "translateY(-500px)";
return (temp = false);
}
});
Here is your working code:
You need to put the n = n - s part into the update number function so its called each time you click.
var s = document.getElementById('incrimentOfNumber').innerHTML
var n = document.getElementById('countdownNumber').innerHTML
document.getElementById("countdownNumber").onclick = function updateNumber() {
n = n - s;
this.innerHTML = n;
}
document.getElementById("resetCountdown").onclick = function resetCountdown(){
n = Math.floor(Math.random() * 500) + 200;
document.getElementById("countdownNumber").innerHTML = n;
}
<h3>Count down from the number you see in incriments of <span class="incrimentOfNumber" id="incrimentOfNumber">7</span>.
<br />Tap the number to see the correct answer.
<br />Repeat as needed.
</h3>
<div class="countdownNumber">
<h1 id="countdownNumber">284</h1>
</div>
<div class="btn" id="resetCountdown">Reset</div>
Before I specify what I am struggling with, let me show you my JavaScript codes.
var gVar = 0;
$("#plus").click(function(e) {
e.preventDefault();
gVar = gVar + 1;
alert(gVar);
});
$("#minus").click(function(e) {
e.preventDefault();
gVar = gVar + 1;
alert(gVar);
});
In the code above, I first set a global variable 'gVar' that holds a integer value of zero. Whenever I click a button whose ID is "plus", the value of the global variable 'gVar' is going to increment by 1, which will be printed out in a browser's dialogue box.
The same thing will happen for the button whose ID is "minus" except that the value of 'gVar' is going to decrement by 1.
In my attempt to tidy up the code above, I created a function separately, which will be called whenever I click the two buttons. Here are the code.
var gVar = 0;
var weird = function (button, Var, num1) {
$(button).click(function(e){
e.preventDefault();
Var = Var + num1;
alert(Var);
});
};
weird("#plus", gVar, 1);
weird("#minus", gVar, -1);
When I run this code, the value of 'gVar' never changes and always stays '0'.
I think I vaguely know what the issue here is, but not entirely sure what is causing this problem. Any input will greatly be appreciated to clarify this issue for me.
Also, I am curious as to if there is any way to create a function to achieve the same effect instead of writing a similar set of code twice for the two different click events.
In JavaScript, only objects are passed as a reference, all other types, including numbers, are copied when you assign them to another variable.
You can instead pass your variable name as a string and then refer to it as window[Var]:
var gVar = 0;
var weird = function (button, Var, num1) {
$(button).click(function(e){
e.preventDefault();
window[Var] = window[Var] + num1;
alert(window[Var]);
});
};
weird("#plus", "gVar", 1);
weird("#minus", "gVar", -1);
As #shiplu.mokadd.im suggested, you can also change gVar to object:
var gVar = {value: 0};
var weird = function (button, Var, num1) {
$(button).click(function(e){
e.preventDefault();
Var.value = Var.value + num1;
alert(Var.value);
});
};
weird("#plus", gVar, 1);
weird("#minus", gVar, -1);
No matter what the function is, you cannot reassign an argument and expect the scope to reflect that change. Depending on the argument however, you can modify it (i.e. if gVar were an object or an array). I suggest you read about pass by reference/value to gain a better understanding of what this means here
the essence of a global variable is that it is global to the whole program, and as such - doesn't need to be passed as argument to any function.
so without modifying too much of your original code
var gVar = 0;
var weird = function (button, num1) {
$(button).click(function(e){
e.preventDefault();
gVar += num1;
alert(Var);
});
};
weird("#plus", 1);
weird("#minus", -1);
var gVar = {
value: 0
};
var weird = function(button, Var, num1) {
$(button).click(function(e) {
e.preventDefault();
Var.value = Var.value + num1;
alert(Var.value);
});
};
weird("#plus", gVar, 1);
weird("#minus", gVar, -1);
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="button" value="+" id="plus">
<br>
<input type="button" value="-" id="minus">