How to get checkbox value unchecked using JS?

Asked

Viewed 256 times

1

Hello, folks, please, I have the following checkbox:

<ul class="nav">
   <li>
      <div>
         <label>Motivo de não informar o nome da mãe</label>
         <br/>
         <input class="messageCheckbox" type="checkbox" id="checkMaeDesconhecida" name="nomeMaeDesc[1][]" value="1"> Desconhecido
         <input class="messageCheckbox" type="checkbox" id="checkNaoTemMae" name="nomeMaeDesc[1][]" value="2"> Não tem
         <input class="messageCheckbox" type="checkbox" checked id="checkMaeNaoInformada" name="nomeMaeDesc[1][]" value="3"> Não Informado
      </div>
   </li>
</ul>

I know this JS command takes the value of my selected combos:

document.querySelector('.messageCheckbox:checked').value

however, I need, if none is selected, I can get some value (type 0). How do I do this?

2 answers

4

Just use the property checked, for example:

const input = document.querySelector('input');

document.querySelector('button').addEventListener('click', () => {
  // A propriedade `checked` retorna um `boolean`.
  console.log(input.checked);
});
<input type="checkbox" />

<button>Obter Valor</button>

  • Thanks, man, your solution I think I was in too, but I found the example of Felipe more suitable for my project, was more relaxed to implement... Quarrel!!

3


Just select all selected checkboxes using the querySelectorAll and checking that its size is greater than zero, as follows:

let checkedBoxes = document.querySelectorAll('.messageCheckbox:checked');
console.log(checkedBoxes > 0);

Following functional example:

function teste() {
  let checkedBoxes = document.querySelectorAll('.messageCheckbox:checked');
  if (checkedBoxes.length > 0) {
    checkedBoxes.forEach(cb => console.log(`A checkbox ${cb.value} está selecionada`));
  } else {
    console.log('Nenhuma checkbox selecionada');
  }
}
<ul class="nav">
   <li>
      <div>
         <label>Motivo de não informar o nome da mãe</label>
         <br/>
         <input class="messageCheckbox" type="checkbox" id="checkMaeDesconhecida" name="nomeMaeDesc[1][]" value="1"> Desconhecido
         <input class="messageCheckbox" type="checkbox" id="checkNaoTemMae" name="nomeMaeDesc[1][]" value="2"> Não tem
         <input class="messageCheckbox" type="checkbox" checked id="checkMaeNaoInformada" name="nomeMaeDesc[1][]" value="3"> Não Informado
      </div>
  </li>
</ul>
<button onclick="teste()">Teste</button>

  • 1

    Wow, man, that’s exactly what I needed, it worked great! Fight!!!

Browser other questions tagged

You are not signed in. Login or sign up in order to post.