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

108
Visualizações
Allow Only Checkboxes in same div to be Checked using jQuery

I have 3 Divs, every div contains 2 inputs, I want to only check checkboxes in the same div with id and unchecked from other divs.

HTML is :

<div class="dashboard">

 <div id="fr">
  <h3>Fruits</h3>
  <label>
   <input type="checkbox" name="check1" />Kiwi</label>
  <label>
   <input type="checkbox" name="check2" />Jackfruit</label>
 </div>

 <div id="an">
  <h3>Animals</h3>
  <label>
   <input type="checkbox" name="check1" />Tiger</label>
  <label>
   <input type="checkbox" name="check2" />Sloth</label>
 </div>

 <div id="veg">
  <h3>vegetables</h3>
  <label>
   <input type="checkbox" name="check1" />Tiger</label>
  <label>
   <input type="checkbox" name="check2" />Sloth</label>
 </div>

</div>

and JQuery is :

$("input:checkbox").on('click', function() {
 var $box = $(this);
 if ($box.is(":checked")) {
  var group = "input:checkbox[name='" + $box.attr("name") + "']";
  $(group).prop("checked", false);
  $box.prop("checked", true);
 } else {
 $box.prop("checked", false);
 }
});

see live example

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

If you only want to allow checkboxes to be checked within a single div, you can use jQuery to traverse the DOM using closest(), siblings() and find() to retrieve the external checkboxes before de-selecting them.

Try this:

$("input:checkbox").on('change', e => {
  $(e.target).closest('div').siblings().find('input:checkbox').prop('checked', false);
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div class="dashboard">
  <div id="fr">
    <h3>Fruits</h3>
    <label><input type="checkbox" name="check1" />Kiwi</label>
    <label><input type="checkbox" name="check2" />Jackfruit</label>
  </div>
  <div id="an">
    <h3>Animals</h3>
    <label><input type="checkbox" name="check1" />Tiger</label>
    <label><input type="checkbox" name="check2" />Sloth</label>
  </div>
  <div id="veg">
    <h3>vegetables</h3>
    <label><input type="checkbox" name="check1" />Tiger</label>
    <label><input type="checkbox" name="check2" />Sloth</label>
  </div>
</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