Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

272
Visualizações
How can I ensure that an if else statement works only if the exact condition is true in javascript?

I have an if/else statement that returns an image if the chicken checkbox is checked, however, if you check the chicken checkbox and another one it still displays the image, how can I set the statement to only display the image only if the chicken checkbox is checked?

The code is as follows:

if (chicken.checked == true) {
  document.getElementById("image").style.visibility = "visible";
} else {  
  return document.getElementById("error").innerHTML = "*Please mark any of checkbox";  
} 
about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

If you want to display the Image only when chicken checkbox is checked , then you should probably test all other checkbox's value in the if/else statement.

about 4 years ago · Juan Pablo Isaza Relatório

0

Initially, in this example, the image is hidden. filter (filter returns an array so you can check its length) on the checked boxes. If the length of the checked boxes is 1, and it's the chicken box, remove the hidden class from the image, otherwise add it back.

Note: the reason I've added a click listener to the container, and haven't added one to each checkbox is to take advantage of event delegation. The container catches the events from the boxes as they bubble up the DOM. That's why we need to check that the element that's been clicked on is an input (using nodeName).

// Cache some elements
const chicken = document.querySelector('#chicken');
const container = document.querySelector('#container');
const boxes = document.querySelectorAll('input[type="checkbox"]');

// Add a listener to the container
container.addEventListener('click', handleBox, false);

function handleBox(e) {

  // Extract the nodeName, and the name of the
  // element that's been checked
  const { nodeName, name } = e.target;

  // If it's an input
  if (nodeName === 'INPUT') {

    // `filter` on the checked boxes
    // `[...boxes]` means convert the nodelist
    // (which doesn't have array methods)
    // to an array, so we can use `filter`
    const checkedBoxes = [...boxes].filter(box => box.checked);

    // If the number of checked boxes is 1,
    // and it's the chicken box...
    if (checkedBoxes.length === 1 && checkedBoxes[0].name === 'chicken') {

      // ...remove the hidden class from the chicken div...
      chicken.classList.remove('hidden');
    } else {

      // ...otherwise add the hidden class back
      chicken.classList.add('hidden');
    }
  }
}
.hidden { visibility: hidden; }
<div id="container">
  <input name="chicken" type="checkbox">
  <label>Chicken</label><br/>
  <input name="mongoose" type="checkbox">
  <label>Mongoose</label><br/>
  <input name="steve" type="checkbox">
  <label>Steve</label><br/>
  <input name="kookaburra" type="checkbox">
  <label>Kookaburra</label><br/>
</div>
<br />
<div id="chicken" class="hidden">Chicken image</div>

about 4 years ago · Juan Pablo Isaza Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda