skip to Main Content

I have the following code

let chosenRating = 0;
for(button in ratingButtons){
    ratingButtons[button].onclick = (e) => {
        chosenRating = e.target.innerHTML;
        
        ratingButtons.forEach(btn => {
            btn.classList.remove('selected');
        })
        e.target.classList.add('selected');
    }
}

I want to be able to access the chosenRating variable globally, but it just says it’s 0. I tried to just declare it and not assign it, but then it says it is undefined. When I console log inside the function, right after assigning it to e.target.innerHTML, I get the value that I want. But outside of the function, I don’t get the same output.

I thought that since I declared the variable globally, even if I don’t assign anything to it then and there, I’ll be able to access the variable globally. How can I fix this so that the innerHTML of the last button I click is stored as the value to the chosenRating variable?

2

Answers


  1. Use var instead let.
    let is a scope variable, so it can’t changed.

    var chosenRating = 0;
    
    Login or Signup to reply.
  2. is ti something like that ?

    const ratingButtons = document.querySelectorAll('button')
      ;
    let chosenRating = 0
      ;
    ratingButtons.forEach( (button,index, ArrBtns ) =>
      {
      button.onclick =_=>
        {
        chosenRating = index;
        ArrBtns.forEach( (btn,indexIn ) =>
          btn.classList.toggle('selected',indexIn===index))
          ;    
        console.clear();
        console.log(`button index is ${chosenRating}`);
        }
      });
    button.selected { background: lightblue; }
    <button class="selected"> A </button>
    <button> B </button>
    <button> C </button>
    <button> D </button>
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search