Uppgift 2

How to repeatedly add +1 to variable on button click?

I have defined a function plusOne() which is supposed to add +1 to a variable (and then set the innerHTML of an element to be that variable). The function is called when a button is clicked. However, the adding of +1 only works once. How do I have to change my function in order to add +1 to the variable every time the button is clicked? Here’s how my function and HTML are looking right now, along with a JSFiddle:

Move var number = 1; outside of the function. You’re resetting it to 1 each time you call the function.

you should also do the same with var count = document.getElementById(‘count’); you dont need to call it everytime

Close voters — this is not a typographical error. This is a conceptual problem in understanding that many people might repeat when new to programming. The typo reason is not a valid CV reason here. However, it is probably a duplicate.

Читайте также:  Css min height absolute position

3 Answers 3

Minimal solution: Move the state variable outside of the click handler’s scope

Change your JavaScript to put the number variable outside of the click handler. Otherwise, you are resetting the number variable to 1 everytime the click handler is called.

var number = 1; function plusOne()

Move the element reference outside the click handler’s scope

It is also a good idea to keep the element reference outside of the click handler’s scope if the element is never destroyed.

var number = 1; var count = document.getElementById('count'); function plusOne()

DOM query lookups are cheap nowadays, but a lot of them will negatively affect your app’s performance.

Make the element dependency explicit

We can even pass the count element to the click handler to make it easier to test.

JavaScript

var number = 1; function plusOne(count)

HTML

The span element is actually assigned to a global variable which is within the scope of the button element just like the plusOne click handler. This means that in all examples, we could just as easily have used count or window.count to access the span element.

Best practice: Add as event listener

It is not recommended to bind the click handler by using the onclick attribute of the button element. One of the reasons is that we are only ever allowed to add one onclick handler, which is not the case with Element#addEventListener .

HTML

JavaScript

var number = 1; var count = document.getElementById('count'); var incrementor = document.getElementById('incrementor'); incrementor.addEventListener('click', plusOne); function plusOne()

Combine best practice with explicit element dependency

We can add a click listener that also passes the count element explicitly to the plusOne function.

var number = 1; var count = document.getElementById('count'); var incrementor = document.getElementById('incrementor'); incrementor.addEventListener('click', function onClick() < plusOne(count); >); function plusOne(count)

Now we are one step closer to maintainable code that is easily tested.

Final solution that is maintainable and easily tested

We can complete our solution by making the second dependency explicit, namely the number state variable.

When we pass this variable to the plusOne function, we now have a pure function which makes it easy to test and reason about.

HTML

JavaScript

var number = 1; var count = document.getElementById('count'); var incrementor = document.getElementById('incrementor'); incrementor.addEventListener('click', function onClick() < number = plusOne(count, number); >); function plusOne(count, number)

While this is more verbose, the dependendencies are clear and the actual business logic, i.e. the plusOne function, can be extracted to a separate file and unit tested to verify that it does what it is supposed to.

Test suite

import < plusOne >from './plus-one'; describe('plusOne', () => < let countElement; let initialState; let state; beforeEach(() =>< initialState = 1; state = initialState; countElement = < textContent: initialState.toString(), >; >) it('returns an incremented state', () => < state = plusOne(countElement, state); expect(state).toBe(initialState + 1); >); it('does not mutate the state', () => < plusOne(countElement, state); expect(state).toBe(initialState); >) it('reflects the state in the count element', () => < state = plusOne(countElement, state); expect(countElement.textContent).toEqual(state.toString()); >); >); 

Anti-pattern: Keep state in DOM

A lot of web apps keep the state in the DOM. While this is easy and we have less mutable state in our code, usually we want access to the state in multiple places of our apps.

Having to extract the state from the DOM in all places where we need it is not how it is supposed to be. We are supposed to keep our business logic in JavaScript and let the DOM reflect the state, not the other way around.

It also adds to a tight coupling to the DOM, making it more difficult to maintain and test.

// Keeping state in DOM is NOT recommended, but here we go. var count = document.getElementById('count'); function plusOne()

Источник

Adding an integer to a JavaScript variable

I added a console log for debugging. It works, so the function is being called, but it is not adding the score. Do I need to parse this to an integer? I can’t work out what the +1 needs to be to work correctly. You can go here and you will see that clicking «Lightning Bolt» for question 1 shows «correct answer» in the console, but doesn’t add to the score variable.

well it seems like you are new to js and posting questions along the way you are working on this quiz app, i suggest making a jsfiddle.net and linking to it from your questions..

5 Answers 5

You just need to assign the +1 to quizScore variable. This may be the fastest way to add 1 and display it in one line

You’re adding one to whatever value is in quizScore , and doing nothing with the result.

You need quizScore = quizScore + 1 .

Keep quizscore as global variable. And secondly change the line no.1 of your correctAnswer() function to

You can use self-memorizing function not to pollute global environment with variables like so:

function correctAnswer() < correctAnswer.quizScore = (correctAnswer.quizScore || 0) + 1; console.log("QuizScore : " + correctAnswer.quizScore); >for (var i = 0; i < 10; i++) < correctAnswer(); // output 1 2 3 4 5 6 7 8 9 10 >

Right now, when you do this:

You add one to it but it doesn’t assign the change to the variable. One reason for this is that sometimes you may want to add a number to the variable long enough to perform an operation but you don’t want it to change.

// quiz score is left alone var nextscore = quizscore + 1 

Here are the different ways to actually assign it:

// temporarily adds 1 to quizscore, then saves it to quizscore quizscore = quizscore + 1 // adds one to quizscore after it's used in an expression quizscore++ // adds one to quizscore before it's used in an expression ++quizscore 

So if you did something like this:

var nextscore = ++quizscore + 1; 

You would both increment the current score and predict the next score.

Источник

Add some text to an existing variable in JS

Because you are re-declaring text variable each time instead of just updating its value. You should do:

var text = ''; text += 'How '; text += 'are '; text += 'you '; text += 'today ?'; alert(text); 

You are redeclaring the variable each time. Drop the extra var s, you only need the first one.

Simply remove the var when you append new value.

var text = ''; text += 'How '; text += 'are '; text += 'you '; text += 'today ?'; alert(text); 

You just use var when you want to declare a JavaScript variable

Each time you use var text , you are re-declaring the variable.

var text = ''; text += 'How '; text += 'are '; text += 'you '; text += 'today ?'; alert(text);

Here’s a different approach, using an array:

var text = []; text.push('How'); text.push('are'); text.push('you'); text.push('today'); alert( text.join(' ') );

I’ll answer in a bit more depth.

The var keyword could be considered a constructor. What a constructor does is creates something, of a class, with all default values. By default, values constructed with the var keyword are null .

With that in mind, what you are doing in reality is redeclaring the text variable as null , and then assigning it your next value, but you are doing this each time you want to add something, therefore appending your new value onto nothing, meaning it is assigned to that value, and that value alone.

This is your solution: (don’t redeclare)

var text = "Hello", name = "Josh"; text += " World"; text += ", My name is "; text += name; 

Источник

Adding +1 to variable

So the way this code is supposed to work is like this, when I click the button I am going to add +1 to the variable antal and the second time when I press the button it should add another +1 making it 2. Now the problem is that every time I push the button I instead get another 1 so the second time I have 11 and the third 111 I’ve tried everything but I cant get it right. I can understand that there is a simple fix to this but I am quite new, thanks in advance for your answers. =)

       

1 Answer 1

The problem is it is interpreting it as a string. You have to force it to be a number with parseInt()

Math.round(parseInt(document.getElementById("antal").value) + 1); 

Hot Network Questions

Subscribe to RSS

To subscribe to this RSS feed, copy and paste this URL into your RSS reader.

Site design / logo © 2023 Stack Exchange Inc; user contributions licensed under CC BY-SA . rev 2023.7.27.43548

By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.

Источник

Оцените статью