David
David

Reputation: 81

How to change variable value when click function is called?

I want to change the check value from false to true whenever I click on the a link. So far I've not found any suggestions on how to do this

<a href="#" class="click"></a>
<a href="#" class="click">Click Me</a>

let check = false;

document.querySelectorAll('.click').forEach(item => {
  item.addEventListener('click', event => {
    check = true;
  });
});

console.log(check);

Upvotes: 0

Views: 207

Answers (2)

McMuffinDK
McMuffinDK

Reputation: 431

Your solution already works, you just have to move your console.log(check) to print the new value

let check = false;

document.querySelectorAll('.click').forEach(item => {
  item.addEventListener('click', event => {

   check = true;
   // print the new value
   console.log(check);
  });
});


console.log(check);
<a href="#" class="click"></a>
<a href="#" class="click">Click Me</a>

Upvotes: 0

Shiny
Shiny

Reputation: 5055

Your console.log() is being executed after you assign the onclick event, not after it is called - So the only thing you log is the value of checked at the very beginning of your script

I've moved the console.log() inside the function, and also added a separate button so you can confirm that the value of check has changed in the global scope

let check = false;

document.querySelectorAll('.click').forEach((item) => {
  item.addEventListener('click', (event) => {
   check = true;
   
   // Check value has changed
   console.log(check);
  });
});
<a href="#" class="click"></a>
<a href="#" class="click">Click Me</a>

<br>
<button style="margin-top: 10px" onclick="console.log(check);">Console.log(check)</button>

Upvotes: 1

Related Questions