Home > Enterprise >  Why text is not showing correct when the value matches
Why text is not showing correct when the value matches

Time:09-29

I was recently generating numbers between 0 & 1 which matches the index of one of the two btn it will be treated as lucky and changes color to green else color changes to red and text will show that other is lucky .

Everything works alright but the text is coorect for 1 btn only , i.e , it will show correct text as I am lucky but not make correct sense for other btn

You can see by clicking the 1st btn : When it is right , i.e , green color text should be "I am lucky" but it shows "Other btn is lucky"

var btnLuck = document.getElementsByTagName("BUTTON");

function randomNumber()
  {
  var randNum = Math.floor(Math.random() * 2);
  document.getElementById("demo").innerHTML = randNum;

console.log('randNum =',randNum ) // ------------------

  for (let i = 0; i < btnLuck.length; i  )
    {
console.log('loop i value-- >', i )  // ------------------
    if (i == randNum)
      {
console.log('(i == randNum) is true')  // ------------------
      document.getElementById("demo").innerHTML = "You are lucky ("   randNum   ")";
      btnLuck[i].style.backgroundColor = "green"
      }
    else 
      {
console.log('(i == randNum) is false') // ------------------
      document.getElementById("demo").innerHTML = "Other btn is lucky ("   randNum   ")";
      btnLuck[i].style.backgroundColor = "red"
  } } }
<button onclick="randomNumber()">Lucky number 0</button>
<button onclick="randomNumber()">Lucky number 1</button>
<div id="demo"></div>

CodePudding user response:

I observed the problem you describe and if you are open to another solution then I hope the following might be of interest.

/*
    Find the DOM elements of interest ~ one is a nodelist
*/
const demo=document.getElementById('demo');
const col=document.querySelectorAll('button');

/*
    assign an event handler to each button found and keep track of the
    buttons DOM nodelist index `i` as we will use that as a comparison
    to the random number generated.
*/
col.forEach((bttn,i)=>bttn.addEventListener('click',function(e){
    // create the random number
  let randNum = Math.floor( Math.random() * 2 );
  
    // output
    let who;
      
    // find the nodelist index of the `other` button
  let index=( ( 1 - i )   1 );
      
    // find the `other` node
  let other=this.parentNode.querySelector('button:nth-of-type(' index ')');
  
    // reset styles for both buttons
  col.forEach(bttn=>bttn.classList.remove('red','green'));
  
  /*
    so if the random number equals the clicked button's nodelist index
    then assign the class and change the class of the `other` element
  */
  if( i===randNum ){
    this.classList.add('green');
    other.classList.add('red');
    who='You are lucky (' randNum ')';
  }else{
    this.classList.add('red');
    other.classList.add('green');
    who='Other btn is lucky (' randNum ')';
  }

  demo.innerText=who;
}));
.red{background:red}
.green{background:green}
button:before{content:'Lucky Number - '}
<button>0</button>
<button>1</button>
<div id="demo"></div>

CodePudding user response:

I suppose you are looking for something like that ?

const
  demo_El  = document.querySelector('#demo')
, buttons  = document.querySelectorAll('button.forRandom') // first is°0 !
, replayBt = document.querySelector('#replay-button')

buttons.forEach( (btn,indexButton) =>
  {
  btn.textContent = `Lucky number ${indexButton  1}` // zero is blown by the wind 
  
  btn.onclick =_=> randomNumberTesting( btn,indexButton )
  })
replayBt.onclick =_=>
  {
  buttons.forEach(bt=>
    {
    bt.classList.remove('win', 'lost')
    bt.disabled = false
    })
  demo_El.textContent = '...?...'
  replayBt.disabled   = true
  }

function randomNumberTesting ( buttonElement, indexButton )
  {
  let randNum = Math.floor(Math.random() *buttons.length) // [0...,n-1]

  buttons.forEach(bt=> bt.disabled = true )

  if (randNum===indexButton)
    {
    demo_El.textContent = `You are lucky (${randNum  1})`
    buttonElement.classList.add('win')
    }
  else
    {
    demo_El.textContent = `"Other btn is lucky (${randNum  1})`
    buttonElement.classList.add('lost')
    buttons[randNum].classList.add('win')
    }
  replayBt.disabled = false
  }
.win  { background: lightgreen; }
.lost { background: lightcoral; }
<button class="forRandom"></button>
<button class="forRandom"></button>
<button class="forRandom"></button>
<button class="forRandom"></button> <!-- or more... -->


<p id="demo">...?...</p>

<button id="replay-button" disabled>replay</button>

  • Related