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

185
Visualizações
How to display a warning message until user tick at least one checkboxes?

I have some checkboxes on the website. If user doesn't tick any of the checkboxes I want to display a warning text on the page (not alert). Once one of the checkboxes ticked this warning will disappear. I wrote following code. This help me to display only on console. However, I want to get some help to display on page itself. Any help is appreciated! PS: I am pretty new in this. Sorry if my question is stupid.

<script>
var array1 = []
const checkboxes=document.querySelectorAll('input[name=group1]:checked')
for (let i = 0; i < checkboxes.length; i++) {
array1.push(checkboxes[i].value)
}
if(array1.length == 0){
console.log("Please select at least one option to process further!")
}    
</script>
about 4 years ago · Juan Pablo Isaza
3 Respostas
Responde à pergunta

0

You add something like <div id="warning"></div> in your html.

And

document.querySelector('#warning').innerText = 'Please select at least one option'; 

in your javascript. Just play around with it.

about 4 years ago · Juan Pablo Isaza Relatório

0

Asuming you have something basically like this in your HTML

<input type="checkbox" name="group1" value="1">
<input type="checkbox" name="group1" value="2">
<input type="checkbox" name="group1" value="3">
<input type="checkbox" name="group1" value="4">
<input type="checkbox" name="group1" value="5">
<div id="warningDiv">Please select at least one option to process further!</div>

At this point you just need to do something like this:

<script>
    if(document.querySelectorAll('input[name=group1]:checked').length == 0)
    {
        //Here you can do an alert or put the text on another html element like a div 
        //For example
        alert("Please select at least one option to process further!")
    }
</script>

The ":checked" is telling the selector to only return the ones that are selected. And the querySelectorAll returns an array of nodes, so you can easily check is lenght to verify is any was selected.

You can play along it if you want to validate one selected, two selected, more than one, etc.

If you paint the message into another element you need to add an else to remove the message.

<script>
    if(document.querySelectorAll('input[name=group1]:checked').length == 0)
    {
        //Here you can do an alert or put the text on another html element like a div 
        //For example
        document.getElementById('warningDiv').innerHTML = "Please select at least one option to process further!";
    }else{
        document.getElementById('warningDiv').innerHTML = "";
    }
</script>

As suggested you can put this into an listener, more or less like this:

function checkChecked()
{
    if(document.querySelectorAll('input[name=group1]:checked').length == 0)
     {
          document.getElementById('warningDiv').innerHTML = "Please select at least one option to process further!";
     }else{
          document.getElementById('warningDiv').innerHTML = "";
     }

}

checkChecked();

const allcheckboxes = document.querySelectorAll('input[name=group1]');
    for(let checkboxinput in allcheckboxes)
    {
        if(typeof allcheckboxes[checkboxinput] == "object" && allcheckboxes[checkboxinput] != null)
        {
          allcheckboxes[checkboxinput].addEventListener('change', function(e) {
            checkChecked()
          });
        }
    }
#warning {
  color: red;
}
<input type="checkbox" name="group1" value="1">
<input type="checkbox" name="group1" value="2">
<input type="checkbox" name="group1" value="3">
<input type="checkbox" name="group1" value="4">
<input type="checkbox" name="group1" value="5">
<div id="warningDiv">Please select at least one option to process further!</div>

about 4 years ago · Juan Pablo Isaza Relatório

0

// query and get elements
const checkboxs = document.querySelectorAll('input[type=checkbox]');
const messages = document.querySelectorAll('.warning');

// add event listener to each element
checkboxs.forEach(checkbox => {
  checkbox.addEventListener("click", () => {
    toggle(checkboxs, messages);
  });
});

// show controlled elements
const show = (elems) => {
  elems.forEach(elem =>
    elem.style.display = 'block'
  );
};

// hide controlled elements
const hide = (elems) => {
  elems.forEach(elem =>
    elem.style.display = 'none'
  );
};

// toggle controlled element visibility according to checkbox state
const toggle = (checkboxs, controlled) => {
  const emptys = [].filter.call(checkboxs, el => !el.checked);
  if (emptys.length == checkboxs.length) {
    show(controlled);
  } else {
    hide(controlled);
  }
};
.warning {
  color: red;
}
<input type='checkbox' value='1'>
<input type='checkbox' value='2'>
<input type='checkbox' value='3'>
<input type='checkbox' value='4'>
<p class='warning'>Please select at least one option to process further!</p>

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