/    Sign up×
Community /Pin to ProfileBookmark

self modified variable in a function

Hello,
I am a beginner at JavaScript and need your help. I’m trying to create a function that will count the number of a variable and display different alerts according to the number.

However, everytime the function is executed, I want the variable number of the previous execution to be kept, here is the script:

[code]
<script language=”JavaScript”>
function cardpick()
{
if (typeof countcard==”undefined”)
{ var countcard = 0 }
var pick=(countcard + 1)
var countcard=(pick)
if (countcard > 3)
{
alert(“You have picked all the cards you needed : “+countcard)}
else {alert(“You have not picked all the cards yet : “+countcard)} }
</script>
[/code]

and the html event:

[code=html]
<a href=”#” onclick=”cardpick()”>Click here</a>
[/code]

Here I try to explain what i did :
function cardpick()
{
if (typeof countcard==”undefined”)
{ var countcard = 0 }
// Here is : if countcard is not defined, then set it at 0, else don’t change anything.
var pick=(countcard + 1)
var countcard=(pick)
// With this I set countcard + 1
if (countcard > 3)
{
alert(“You have picked all the cards you needed : “+countcard)}
else {alert(“You have not picked all the cards yet : “+countcard)} }

Here, on click we get the messages, however, I want that everytime we click on the link, +1 is added. So first time you click on the link, you get ‘You have not picked all the cards yet : 1’

Second time you click on the link :
‘You have not picked all the cards yet : 2’

Third time you click :
‘You have not picked all the cards yet : 3’

fourth time and more :
‘You have picked all the cards you needed : 4.etc…’

With my script, variable countcard is always 1 :-(.
Do you know what’s wrong ?, thanks for your help.

Gafir

to post a comment
JavaScript

1 Comments(s)

Copy linkTweet thisAlerts:
@FangMar 23.2007 — Why so complicated?var countcard=0;
function cardpick() {
if (++countcard &gt; 3) {
alert("You have picked all the cards you needed : "+countcard);
}
else {
alert("You have not picked all the cards yet : "+countcard);
}
}
Variable scope
×

Success!

Help @gafir777 spread the word by sharing this article on Twitter...

Tweet This
Sign in
Forgot password?
Sign in with TwitchSign in with GithubCreate Account
about: ({
version: 0.1.9 BETA 6.17,
whats_new: community page,
up_next: more Davinci•003 tasks,
coming_soon: events calendar,
social: @webDeveloperHQ
});

legal: ({
terms: of use,
privacy: policy
});
changelog: (
version: 0.1.9,
notes: added community page

version: 0.1.8,
notes: added Davinci•003

version: 0.1.7,
notes: upvote answers to bounties

version: 0.1.6,
notes: article editor refresh
)...
recent_tips: (
tipper: @nearjob,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,

tipper: @meenaratha,
tipped: article
amount: 1000 SATS,
)...