0

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);
10
  • Use the onClick event w3schools.com/jsref/tryit.asp?filename=tryjsref_onclick stackoverflow.com/a/14867603/495157 Commented Dec 24, 2019 at 16:07
  • This works as it is - move the console.log(check) inside the eventListener Commented Dec 24, 2019 at 16:09
  • @Light thanks but I want to change value in global. Commented Dec 24, 2019 at 16:11
  • You are changing it in the global scope Commented Dec 24, 2019 at 16:11
  • @David your console.log(check) gets executed right after you define your click event. It's not being called after you click or any other time after. If you look at your check variable after you've clicked, you'll find it's been set. You could add another click link that checks the value and shows it to the user in HTML or an alert if you want to test it out Commented Dec 24, 2019 at 16:12

2 Answers 2

1

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>

Sign up to request clarification or add additional context in comments.

Comments

0

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>

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.