AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / coding / Perguntas / 79578302
Accepted
cool
cool
Asked: 2025-04-17 08:56:32 +0800 CST2025-04-17 08:56:32 +0800 CST 2025-04-17 08:56:32 +0800 CST

Desabilitando caixas de seleção no Jquery quando qualquer caixa de seleção é clicada

  • 772

Tenho a seguinte série de caixas de seleção na minha página:

$("#chkLoc0").click(function() {
  $('[id^=chkLoc]:not(#chkLoc0)').prop('checked', $(this).prop('checked'));
});
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<div class="form-group row" id="Location">
  <div class="col">
    <label class="checkbox-inline">
 <input  type="checkbox" id="chkLoc0" name="Locations[0].SelectedSection" value="1"  />
  Any  <br />
 </label>
    <label class="checkbox-inline">
 <input  type="checkbox" id="chkLoc1" name="Locations[0].SelectedSection" value="2"  />
  Test1  <br />
 </label>
    <label class="checkbox-inline">
 <input  type="checkbox" id="chkLoc2" name="Locations[0].SelectedSection" value="3"  />
  Test2  <br />
 </label>
    <label class="checkbox-inline">
 <input  type="checkbox" id="chkLoc3" name="Locations[0].SelectedSection" value="4"  />
  Test3  <br />
 </label>
    <label class="checkbox-inline">
 <input  type="checkbox" id="chkLoc4" name="Locations[0].SelectedSection" value="5"  />
  Test4  <br />
 </label>
  </div>

Se o usuário marcar a caixa "Qualquer", quero que as demais caixas sejam marcadas e também que as demais caixas de seleção sejam desativadas. É isso que preciso marcar para as demais caixas de seleção se "Qualquer" for clicado e funcionar.

 $("#chkLoc0").click(function () {
       $('[id^=chkLoc]:not(#chkLoc0)').prop('checked', $(this).prop('checked'));
   });

Tentei escrever o código abaixo para desabilitar o restante das caixas de seleção se "Qualquer" for clicado, mas não está funcionando. Eis o que eu tenho:

  $("#chkLoc0").click(function () {
       $('[id^=chkLoc]:not(#chkLoc0)').prop('disabled', $(this).prop('disabled'));
   });

Como posso desabilitar todas as caixas de seleção quando a caixa de seleção "Qualquer" estiver marcada? Estou apenas tentando fazer com que, se a caixa de seleção "Qualquer" estiver marcada, todas as caixas de seleção permaneçam marcadas. Não quero que o usuário clique na caixa de seleção "Qualquer" e depois desmarque algumas caixas de seleção, como "Teste1" e "Teste2". Quero garantir que, se "Qualquer" for marcado, "Teste1", "Teste2", "Teste3" e "Teste4" permaneçam marcadas. Às vezes, o usuário clica na caixa de seleção "Qualquer" e depois desmarca uma ou duas caixas de seleção. Quero desabilitar "Teste1", "Teste2", "Teste3" e "Teste4" para que permaneçam marcadas.

javascript
  • 3 3 respostas
  • 76 Views

3 respostas

  • Voted
  1. Lajos Arpad
    2025-04-17T09:52:56+08:002025-04-17T09:52:56+08:00

    Basta usar propsdentro de um clickevento para Any, encontrar as outras caixas de seleção e alterar suas propriedades com base na propriedade marcada.

    $("#chkLoc0").click(function() {
        $("#chkLoc1, #chkLoc2, #chkLoc3, #chkLoc4").prop('checked', $(this).prop('checked')).prop('disabled', $(this).prop('checked'));
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <div class="form-group row" id="Location">
                        <div class="col">
    
     <label class="checkbox-inline">
     <input  type="checkbox" id="chkLoc0" name="Locations[0].SelectedSection" value="1"  />
      Any  <br />
     </label>
     <label class="checkbox-inline">
     <input  type="checkbox" id="chkLoc1" name="Locations[0].SelectedSection" value="2"  />
      Test1  <br />
     </label>
     <label class="checkbox-inline">
     <input  type="checkbox" id="chkLoc2" name="Locations[0].SelectedSection" value="3"  />
      Test2  <br />
     </label>
     <label class="checkbox-inline">
     <input  type="checkbox" id="chkLoc3" name="Locations[0].SelectedSection" value="4"  />
      Test3  <br />
     </label>
    <label class="checkbox-inline">
     <input  type="checkbox" id="chkLoc4" name="Locations[0].SelectedSection" value="5"  />
      Test4  <br />
     </label>
    </div>

    Exemplo com classe:

        $("#chkLoc0").click(function() {
            $(".checkbox").prop('checked', $(this).prop('checked')).prop('disabled', $(this).prop('checked'));
        });
        <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
        <div class="form-group row" id="Location">
                            <div class="col">
    
         <label class="checkbox-inline">
         <input  type="checkbox" id="chkLoc0" name="Locations[0].SelectedSection" value="1"  />
          Any  <br />
         </label>
         <label class="checkbox-inline">
         <input  type="checkbox" class="checkbox" id="chkLoc1" name="Locations[0].SelectedSection" value="2"  />
          Test1  <br />
         </label>
         <label class="checkbox-inline">
         <input  type="checkbox" class="checkbox" id="chkLoc2" name="Locations[0].SelectedSection" value="3"  />
          Test2  <br />
         </label>
         <label class="checkbox-inline">
         <input  type="checkbox" class="checkbox" id="chkLoc3" name="Locations[0].SelectedSection" value="4"  />
          Test3  <br />
         </label>
        <label class="checkbox-inline">
         <input  type="checkbox" class="checkbox" id="chkLoc4" name="Locations[0].SelectedSection" value="5"  />
          Test4  <br />
         </label>
        </div>

    Uma abordagem alternativa é fazer com que a caixa de seleção Qualquer responda à marcação e desmarcação de outras caixas de seleção:

    $("#chkLoc0").click(function() {
        $("#chkLoc1, #chkLoc2, #chkLoc3, #chkLoc4").prop('checked', $(this).prop('checked')).prop('disabled', $(this).prop('checked'));
    });
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
    <div class="form-group row" id="Location">
                        <div class="col">
    
     <label class="checkbox-inline">
     <input  type="checkbox" id="chkLoc0" name="Locations[0].SelectedSection" value="1"  />
      Any  <br />
     </label>
     <label class="checkbox-inline">
     <input  type="checkbox" id="chkLoc1" name="Locations[0].SelectedSection" value="2"  />
      Test1  <br />
     </label>
     <label class="checkbox-inline">
     <input  type="checkbox" id="chkLoc2" name="Locations[0].SelectedSection" value="3"  />
      Test2  <br />
     </label>
     <label class="checkbox-inline">
     <input  type="checkbox" id="chkLoc3" name="Locations[0].SelectedSection" value="4"  />
      Test3  <br />
     </label>
    <label class="checkbox-inline">
     <input  type="checkbox" id="chkLoc4" name="Locations[0].SelectedSection" value="5"  />
      Test4  <br />
     </label>
    </div>

    Exemplo com classe:

    /*$("#chkLoc0").click(function() {
            $(".checkbox").prop('checked', $(this).prop('checked')).prop('disabled', $(this).prop('checked'));
        });*/
    
    let subsequentCheckboxes = document.getElementsByClassName("checkbox");
    let anyCheckbox = document.getElementById("chkLoc0");
    anyCheckbox.addEventListener("change", function() {
        for (let subsequentCheckbox of subsequentCheckboxes) {
            subsequentCheckbox.checked = this.checked;
        }
    });
    
    for (let subsequentCheckbox of subsequentCheckboxes) {
        subsequentCheckbox.addEventListener("change", function() {
            let checkedCount = document.querySelectorAll(".checkbox:checked").length;
            anyCheckbox.checked = (checkedCount === subsequentCheckboxes.length);
        });
    }
    <div class="form-group row" id="Location">
                            <div class="col">
    
         <label class="checkbox-inline">
         <input  type="checkbox" id="chkLoc0" name="Locations[0].SelectedSection" value="1"  />
          Any  <br />
         </label>
         <label class="checkbox-inline">
         <input  type="checkbox" class="checkbox" id="chkLoc1" name="Locations[0].SelectedSection" value="2"  />
          Test1  <br />
         </label>
         <label class="checkbox-inline">
         <input  type="checkbox" class="checkbox" id="chkLoc2" name="Locations[0].SelectedSection" value="3"  />
          Test2  <br />
         </label>
         <label class="checkbox-inline">
         <input  type="checkbox" class="checkbox" id="chkLoc3" name="Locations[0].SelectedSection" value="4"  />
          Test3  <br />
         </label>
        <label class="checkbox-inline">
         <input  type="checkbox" class="checkbox" id="chkLoc4" name="Locations[0].SelectedSection" value="5"  />
          Test4  <br />
         </label>
        </div>

    • 3
  2. Best Answer
    Wimanicesir
    2025-04-17T20:56:00+08:002025-04-17T20:56:00+08:00

    A resposta aceita para mim é simplesmente algo que funciona, mas, na minha opinião, não é a melhor abordagem. Antes de mais nada, eu recomendo fortemente parar de usar jQuery e migrar para JS comum.

    Mesmo que seu projeto já esteja usando jQuery, pode não ser uma má ideia começar a usar JS normal para que você possa mudar quando todo o jQuery estiver disponível.

    Esta resposta fornece uma abordagem mais lógica. (IMO)

    1. Quando 'ALL' for selecionado, selecione tudo e vice-versa
    2. Quando uma caixa de seleção for removida de toda a seleção, desmarque também Tudo (e sim, também vice-versa)

    // Checkboxes aren't dynamic, so retrieve them once
    const checkboxes = document.querySelectorAll(".checkbox-inline input");
    const allButton = document.querySelector("#chkLoc0");
    const checkboxesExceptAll = [...checkboxes].filter(cb => cb !== allButton);
    
    // When the "All" checkbox is changed, apply its state to all others
    allButton.addEventListener("change", () => {
      checkboxes.forEach(checkbox => {
        checkbox.checked = allButton.checked;
      });
    });
    
    // Add change listener to each checkbox except the "All" checkbox
    checkboxesExceptAll.forEach(checkbox => {
        checkbox.addEventListener("change", () => {
          // If any individual checkbox is unchecked, uncheck the "All" checkbox
          if (checkboxesExceptAll.every(cb => cb.checked)) {
            allButton.checked = true;
          } else {
            allButton.checked = false;
          }
        });
    });
    <div class="form-group row" id="Location">
     <div class="col">
       <label class="checkbox-inline">
         <input type="checkbox" id="chkLoc0" name="Locations[0].SelectedSection" value="1" /> All <br />
       </label>
       <label class="checkbox-inline">
         <input type="checkbox" class="checkbox" id="chkLoc1" name="Locations[0].SelectedSection" value="2" /> Test1 <br />
       </label>
       <label class="checkbox-inline">
         <input type="checkbox" class="checkbox" id="chkLoc2" name="Locations[0].SelectedSection" value="3" /> Test2 <br />
       </label>
       <label class="checkbox-inline">
         <input type="checkbox" class="checkbox" id="chkLoc3" name="Locations[0].SelectedSection" value="4" /> Test3 <br />
       </label>
       <label class="checkbox-inline">
         <input type="checkbox" class="checkbox" id="chkLoc4" name="Locations[0].SelectedSection" value="5" /> Test4 <br />
       </label>
     </div>

    • 1
  3. chrwahl
    2025-04-18T00:08:15+08:002025-04-18T00:08:15+08:00

    Entendo que você gostaria que a caixa de seleção "Qualquer" fosse consistente com as demais, mas um padrão comum em casos como este é que o usuário pode marcar todas (usando "Qualquer") e depois desmarcar uma ou mais das outras. Portanto, certifique-se de desmarcar "Qualquer" se alguma das outras estiver desmarcada.

    document.forms.form01.addEventListener('change', e => {
      let form = e.target.form;
      switch (e.target.id) {
        case 'chkLoc0':
          [...form.others.elements].forEach(input => input.checked = e.target.checked);
          break;
        default:
          let otherschecked = ([...form.others.elements]
            .filter(input => !input.checked).length == 0) ?? true;
          form.chkLoc0.checked = otherschecked;
          break;
      }
    });
    fieldset {
      border: none;
      padding: 0;
      margin: 0;
      display: flex;
      flex-direction: column;
    }
    <form name="form01">
      <div class="form-group row" id="Location">
        <label class="checkbox-inline"><input type="checkbox" id="chkLoc0"
          name="Locations[0].SelectedSection" value="1">Any</label>
        <fieldset name="others">
          <label class="checkbox-inline"><input type="checkbox" id="chkLoc1"
            name="Locations[0].SelectedSection" value="2">Test1</label>
          <label class="checkbox-inline"><input type="checkbox" id="chkLoc2"
            name="Locations[0].SelectedSection" value="3">Test2</label>
          <label class="checkbox-inline"><input type="checkbox" id="chkLoc3"
            name="Locations[0].SelectedSection" value="4">Test3</label>
          <label class="checkbox-inline"><input type="checkbox" id="chkLoc4"
            name="Locations[0].SelectedSection" value="5">Test4</label>
        </fieldset>
      </div>
    </form>

    E então a alternativa que você pede:

    document.forms.form01.addEventListener('change', e => {
      let form = e.target.form;
      switch (e.target.id) {
        case 'chkLoc0':
          [...form.others.elements].forEach(input => {
            input.checked = e.target.checked;
            input.disabled = e.target.checked;
          });
          break;
        default:
          let otherschecked = ([...form.others.elements]
            .filter(input => !input.checked).length == 0) ?? true;
          form.chkLoc0.checked = otherschecked;
          [...form.others.elements].forEach(input => input.disabled = otherschecked);
          break;
      }
    });
    fieldset {
      border: none;
      padding: 0;
      margin: 0;
      display: flex;
      flex-direction: column;
    }
    <form name="form01">
      <div class="form-group row" id="Location">
        <label class="checkbox-inline"><input type="checkbox" id="chkLoc0"
          name="Locations[0].SelectedSection" value="1">Any</label>
        <fieldset name="others">
          <label class="checkbox-inline"><input type="checkbox" id="chkLoc1"
            name="Locations[0].SelectedSection" value="2">Test1</label>
          <label class="checkbox-inline"><input type="checkbox" id="chkLoc2"
            name="Locations[0].SelectedSection" value="3">Test2</label>
          <label class="checkbox-inline"><input type="checkbox" id="chkLoc3"
            name="Locations[0].SelectedSection" value="4">Test3</label>
          <label class="checkbox-inline"><input type="checkbox" id="chkLoc4"
            name="Locations[0].SelectedSection" value="5">Test4</label>
        </fieldset>
      </div>
    </form>

    • 1

relate perguntas

  • classificação de mesclagem não está funcionando - código Javascript: não é possível encontrar o erro mesmo após a depuração

  • método select.remove() funciona estranho [fechado]

  • Sempre um 401 res em useOpenWeather () - react-open-weather lib [duplicado]

  • O elemento de entrada não possui atributo somente leitura, mas os campos ainda não podem ser editados [fechado]

  • Como editar o raio do primeiro nó de um RadialTree D3.js?

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    Reformatar números, inserindo separadores em posições fixas

    • 6 respostas
  • Marko Smith

    Por que os conceitos do C++20 causam erros de restrição cíclica, enquanto o SFINAE antigo não?

    • 2 respostas
  • Marko Smith

    Problema com extensão desinstalada automaticamente do VScode (tema Material)

    • 2 respostas
  • Marko Smith

    Vue 3: Erro na criação "Identificador esperado, mas encontrado 'import'" [duplicado]

    • 1 respostas
  • Marko Smith

    Qual é o propósito de `enum class` com um tipo subjacente especificado, mas sem enumeradores?

    • 1 respostas
  • Marko Smith

    Como faço para corrigir um erro MODULE_NOT_FOUND para um módulo que não importei manualmente?

    • 6 respostas
  • Marko Smith

    `(expression, lvalue) = rvalue` é uma atribuição válida em C ou C++? Por que alguns compiladores aceitam/rejeitam isso?

    • 3 respostas
  • Marko Smith

    Um programa vazio que não faz nada em C++ precisa de um heap de 204 KB, mas não em C

    • 1 respostas
  • Marko Smith

    PowerBI atualmente quebrado com BigQuery: problema de driver Simba com atualização do Windows

    • 2 respostas
  • Marko Smith

    AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos

    • 1 respostas
  • Martin Hope
    Fantastic Mr Fox Somente o tipo copiável não é aceito na implementação std::vector do MSVC 2025-04-23 06:40:49 +0800 CST
  • Martin Hope
    Howard Hinnant Encontre o próximo dia da semana usando o cronógrafo 2025-04-21 08:30:25 +0800 CST
  • Martin Hope
    Fedor O inicializador de membro do construtor pode incluir a inicialização de outro membro? 2025-04-15 01:01:44 +0800 CST
  • Martin Hope
    Petr Filipský Por que os conceitos do C++20 causam erros de restrição cíclica, enquanto o SFINAE antigo não? 2025-03-23 21:39:40 +0800 CST
  • Martin Hope
    Catskul O C++20 mudou para permitir a conversão de `type(&)[N]` de matriz de limites conhecidos para `type(&)[]` de matriz de limites desconhecidos? 2025-03-04 06:57:53 +0800 CST
  • Martin Hope
    Stefan Pochmann Como/por que {2,3,10} e {x,3,10} com x=2 são ordenados de forma diferente? 2025-01-13 23:24:07 +0800 CST
  • Martin Hope
    Chad Feller O ponto e vírgula agora é opcional em condicionais bash com [[ .. ]] na versão 5.2? 2024-10-21 05:50:33 +0800 CST
  • Martin Hope
    Wrench Por que um traço duplo (--) faz com que esta cláusula MariaDB seja avaliada como verdadeira? 2024-05-05 13:37:20 +0800 CST
  • Martin Hope
    Waket Zheng Por que `dict(id=1, **{'id': 2})` às vezes gera `KeyError: 'id'` em vez de um TypeError? 2024-05-04 14:19:19 +0800 CST
  • Martin Hope
    user924 AdMob: MobileAds.initialize() - "java.lang.Integer não pode ser convertido em java.lang.String" para alguns dispositivos 2024-03-20 03:12:31 +0800 CST

Hot tag

python javascript c++ c# java typescript sql reactjs html

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve