how to get the values from two inputs and write an output message if they are equal values or not?

Raquel Santos :

This is what I been doing so far. The problem is that the message appears always even without value input. Another thing, would you do this differently? if yes show me your examples.

let jogador1 = document.querySelector('#jogador1');
let jogador2 =document.querySelector('#jogador2');
let output = document.querySelector('#output');


let value1 = jogador1.value;
let value2 = jogador2.value;

let letsCompareValues = (value1, value2) => {

       if (value1 === value2 && value1 !== isNaN && value2 !==isNaN) {
           msg += ' there is a match';
           return output.textContent = msg;
       }


}

button.addEventListener('click', letsCompareValues(value1, value2));

            <div>
                <label for="jogador1">Player 1</label>
                <input type="text" id="jogador1">
            </div>
            <div>
                <label for="jogador2">Player 2</label>
                <input type="text" id="jogador2">
            </div>
            <button id="button">JOGAR</button>


palaѕн :

The issue is you have set the value before button click only like:

let value1 = jogador1.value;
let value2 = jogador2.value;

So, even if the user changes these values.. the temp values stored in value1 & value2 will always be empty. You just need to access those values inside button click only like:

let letsCompareValues = () => {
  let msg = '';
  let value1 = jogador1.value;
  let value2 = jogador2.value;
  if (value1 === value2 && !isNaN(value1) && !isNaN(value2)) {
    msg += ' there is a match';
    output.textContent = msg;
    return output.textContent;
  } else {
    output.textContent = msg;
  }
}

DEMO:

let jogador1 = document.querySelector('#jogador1');
let jogador2 = document.querySelector('#jogador2');
let output = document.querySelector('#output');

let letsCompareValues = () => {
  let msg = '';
  let value1 = jogador1.value;
  let value2 = jogador2.value;
  if (value1 === value2 && !isNaN(value1) && !isNaN(value2)) {
    msg += ' there is a match';
    output.textContent = msg;
    return output.textContent;
  } else {
    output.textContent = msg;
  }
}

button.addEventListener('click', letsCompareValues);
<div>
  <label for="jogador1">Player 1</label>
  <input type="text" id="jogador1">
</div>
<div>
  <label for="jogador2">Player 2</label>
  <input type="text" id="jogador2">
</div>

<button id="button">JOGAR</button>
<div id="output">
</div>

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=398571&siteId=1