Włączanie / wyłączanie pól wyboru

Mam następujące:

$(document).ready(function()
{
    $("#select-all-teammembers").click(function() {
        $("input[name=recipients\\[\\]]").attr('checked', true);
    });                 
});

Chciałbym id="select-all-teammembers" po kliknięciu przełączać się między zaznaczonymi i niezaznaczonymi. Pomysły? to nie są dziesiątki linijek kodu?

Author: neophyte, 2010-11-14

23 answers

Możesz napisać:

$(document).ready(function() {
    $("#select-all-teammembers").click(function() {
        var checkBoxes = $("input[name=recipients\\[\\]]");
        checkBoxes.prop("checked", !checkBoxes.prop("checked"));
    });                 
});

Przed jQuery 1.6, kiedy mieliśmy tylko attr () a nie prop () , pisaliśmy:

checkBoxes.attr("checked", !checkBoxes.attr("checked"));

Ale prop() ma lepszą semantykę niż attr(), gdy jest zastosowana do "boolean" atrybutów HTML, więc jest zwykle preferowana w tej sytuacji.

 635
Author: Frédéric Hamidi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-03-12 21:48:58
//this toggles the checkbox, and fires its event if it has    

$('input[type=checkbox]').trigger('click'); 
//or
$('input[type=checkbox]').click(); 
 189
Author: ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-01-07 21:54:34

Wiem, że to stare, ale pytanie było nieco niejednoznaczne, ponieważ przełączanie może oznaczać, że każde pole wyboru powinno przełączać swój stan, cokolwiek to jest. Jeśli masz 3 zaznaczone i 2 niezaznaczone, to przełączanie spowoduje, że pierwsze 3 niezaznaczone, a ostatnie 2 zaznaczone.

W tym celu żadne z rozwiązań tutaj nie działa, ponieważ sprawiają, że wszystkie pola wyboru mają ten sam stan, zamiast przełączać stan każdego z nich. Robienie $(':checkbox').prop('checked') na wielu polach wyboru zwraca logiczne i pomiędzy wszystkimi .checked binarne właściwości, tzn. jeśli jedna z nich nie jest zaznaczona, zwracaną wartością jest false.

Musisz użyć .each(), Jeśli chcesz rzeczywiście przełączyć każdy stan checkboxa, a nie sprawić, by wszystkie były równe, np.

   $(':checkbox').each(function () { this.checked = !this.checked; });

Zauważ, że nie potrzebujesz $(this) wewnątrz funkcji obsługi, ponieważ właściwość .checked istnieje we wszystkich przeglądarkach.

 55
Author: Normadize,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-04-17 16:41:15

Oto inny sposób, który chcesz.

$(document).ready(function(){   
    $('#checkp').toggle(
        function () { 
            $('.check').attr('Checked','Checked'); 
        },
        function () { 
            $('.check').removeAttr('Checked'); 
        }
    );
});
 15
Author: kst,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2010-11-14 11:36:49

Myślę, że prościej jest po prostu uruchomić kliknięcie:

$("#select-all-teammembers").click(function() {
    $("input[name=recipients\\[\\]]").trigger('click');
});                 
 8
Author: matt burns,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-06-04 14:52:00

Od jQuery 1.6 możesz używać .prop(function) aby włączyć sprawdzany stan każdego znalezionego elementu:

$("input[name=recipients\\[\\]]").prop('checked', function(_, checked) {
    return !checked;
});
 7
Author: Ja͢ck,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-03-17 07:23:18

Użyj tej wtyczki:

$.fn.toggleCheck  =function() {
       if(this.tagName === 'INPUT') {
           $(this).prop('checked', !($(this).is(':checked')));
       }

   }

Then

$('#myCheckBox').toggleCheck();
 6
Author: Abdennour TOUMI,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-07-10 17:24:05

Najlepszy sposób, jaki mogę wymyślić.

$('#selectAll').change(function () {
    $('.reportCheckbox').prop('checked', this.checked);
});

Lub

$checkBoxes = $(".checkBoxes");
$("#checkAll").change(function (e) {
    $checkBoxes.prop("checked", this.checked);
});   

Lub

<input onchange="toggleAll(this)">
function toggleAll(sender) {
    $(".checkBoxes").prop("checked", sender.checked);
}
 4
Author: Dblock247,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2018-01-22 15:47:21

Zakładając, że jest to obrazek, który musi przełączyć pole wyboru, działa to dla mnie

<img src="something.gif" onclick="$('#checkboxid').prop('checked', !($('#checkboxid').is(':checked')));">
<input type="checkbox" id="checkboxid">
 2
Author: user1428592,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2012-05-31 14:32:37

Zaznaczenie-wszystkie pole wyboru powinno być zaktualizowane samo pod pewnymi warunkami. Spróbuj kliknąć na '# select-all-teamembers', następnie odznaczyć kilka elementów i ponownie kliknąć select-all. Widać niespójność. Aby temu zapobiec, użyj następującego triku:

  var checkBoxes = $('input[name=recipients\\[\\]]');
  $('#select-all-teammembers').click(function() {
    checkBoxes.prop("checked", !checkBoxes.prop("checked"));
    $(this).prop("checked", checkBoxes.is(':checked'));
  }); 

BTW wszystkie pola wyboru DOM-obiekt powinny być buforowane w sposób opisany powyżej.

 2
Author: Anatoly,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-09-26 13:51:43
jQuery("#checker").click(function(){
    jQuery("#mydiv :checkbox").each(function(){
        this.checked = true;
    });
});
jQuery("#dechecker").click(function(){
    jQuery("#mydiv :checkbox").each(function(){
        this.checked = false;
    });
});
jQuery("#checktoggler").click(function(){
    jQuery("#mydiv :checkbox").each(function(){
        this.checked = !this.checked;
    });
});

;)

 1
Author: GigolNet Guigolachvili,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-09-05 21:23:05

Możesz napisać tak również

$(function() {
    $("#checkbox-toggle").click(function() {
        $('input[type=checkbox][name=checkbox_id\\[\\]]').click();
    });
});

Wystarczy wywołać zdarzenie click of check box, gdy użytkownik kliknie przycisk o id '# checkbox-toggle'.

 1
Author: Milan Malani,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-05-19 04:07:40

Lepsze podejście i UX

$('.checkall').on('click', function() {
   var $checks  = $('checks');
   var $ckall = $(this);

    $.each($checks, function(){
        $(this).prop("checked", $ckall.prop('checked'));
    });
});

$('checks').on('click', function(e){
   $('.checkall').prop('checked', false);
});
 1
Author: Hugo Dias,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-05-20 18:02:47
<table class="table table-datatable table-bordered table-condensed table-striped table-hover table-responsive">
<thead>
    <tr>
        <th class="col-xs-1"><a class="select_all btn btn-xs btn-info"> Select All </a></th>
        <th class="col-xs-2">#ID</th>
    </tr>
</thead>
<tbody>
    <tr>
        <td><input type="checkbox" name="order333"/></td>
        <td>{{ order.id }}</td>
    </tr>
    <tr>
        <td><input type="checkbox" name="order334"/></td>
        <td>{{ order.id }}</td>
    </tr>
</tbody>                  
</table>

Try:

$(".table-datatable .select_all").on('click', function () {
    $("input[name^='order']").prop('checked', function (i, val) {
        return !val;
    });
});
 1
Author: Karol Gontarski,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2015-06-09 11:48:27

Najbardziej podstawowym przykładem może być:

// get DOM elements
var checkbox = document.querySelector('input'),
    button = document.querySelector('button');

// bind "cilck" event on the button
button.addEventListener('click', toggleCheckbox);

// when clicking the button, toggle the checkbox
function toggleCheckbox(){
  checkbox.checked = !checkbox.checked;
};
<input type="checkbox">
<button>Toggle checkbox</button>
 1
Author: vsync,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-07-17 21:39:40

Po prostu możesz użyć tego

$("#chkAll").on("click",function(){
    $("input[name=checkBoxName]").prop("checked",$(this).prop("checked"));
});
 1
Author: Fouad Mekkey,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2017-09-28 09:02:37

Jeśli chcesz przełączać każde pudełko z osobna (lub tylko jedno działa równie dobrze):

Polecam korzystanie .each (), ponieważ jest łatwy do modyfikacji, jeśli chcesz, aby wydarzyły się różne rzeczy, i nadal stosunkowo krótki i łatwy do odczytania.

Np.:

// toggle all checkboxes, not all at once but toggle each one for its own checked state:
$('input[type="checkbox"]').each(function(){ this.checked = ! this.checked });

// check al even boxes, uncheck all odd boxes:
$('input[type="checkbox"]').each(function(i,cb){ cb.checked = (i%2 == 0); });

// set all to checked = x and only trigger change if it actually changed:
x = true;
$('input[type="checkbox"]').each(function(){
    if(this.checked != x){ this.checked = x; $(this).change();}  
});
Na marginesie... Nie wiem, dlaczego wszyscy używają .attr () lub .prop () to (un) check things.

Z tego co wiem, element.sprawdzony zawsze działał tak samo we wszystkich przeglądarkach?

 0
Author: MoonLite,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-06-18 12:42:28

Według mnie najodpowiedniejszym człowiekiem, który zasugerował normalny wariant jest GigolNet Gigolashvili, ale chcę zasugerować jeszcze piękniejszy wariant. Sprawdź to

$(document).on('click', '.fieldWrapper > label', function(event) {
    event.preventDefault()
    var n = $( event.target ).parent().find('input:checked').length
    var m = $( event.target ).parent().find('input').length
    x = n==m? false:true
    $( event.target ).parent().find('input').each(function (ind, el) {
        // $(el).attr('checked', 'checked');
        this.checked = x
    })
})
 0
Author: Arthur Sult,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-01-01 05:29:56

Ustawienie 'checked' lub null zamiast odpowiednio true lub false wykona pracę.

// checkbox selection
var $chk=$(':checkbox');
$chk.prop('checked',$chk.is(':checked') ? null:'checked');
 0
Author: I.P.Singh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2014-01-28 05:24:17

Dla mnie to działa bardzo dobrze.

   $("#checkall").click(function() {
       var fruits = $("input[name=fruits\\[\\]]");
        fruits.prop("checked", $(this).prop("checked"));
    });
 0
Author: sovantha,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-01-05 15:57:01

Ten kod przełącza pole wyboru po kliknięciu dowolnego animatora przełącznika używanego w szablonach internetowych. Replace".onoffswitch-Etykieta " dostępna w Twoim kodzie. "checkboxID" to pole wyboru włączone tutaj.

$('.onoffswitch-label').click(function () {
if ($('#checkboxID').prop('checked')) 
 {
   $('#checkboxID').prop('checked', false);
 }
else 
 {
   $('#checkboxID').prop('checked', true);
 }
});
 0
Author: Pranesh Janarthanan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-12 13:03:00

Oto sposób jQuery na przełączanie pól wyboru bez konieczności zaznaczania pola wyboru z etykietami html5:

 <div class="checkbox-list margin-auto">
    <label class="">Compare to Last Year</label><br>
    <label class="normal" for="01">
       <input id="01" type="checkbox" name="VIEW" value="01"> Retail units
    </label>
    <label class="normal" for="02">
          <input id="02" type="checkbox" name="VIEW" value="02">  Retail Dollars
    </label>
    <label class="normal" for="03">
          <input id="03" type="checkbox" name="VIEW" value="03">  GP Dollars
    </label>
    <label class="normal" for="04">
          <input id="04" type="checkbox" name="VIEW" value="04">  GP Percent
    </label>
</div>

  $("input[name='VIEW']:checkbox").change(function() {
    if($(this).is(':checked')) {  
         $("input[name='VIEW']:checkbox").prop("checked", false);
     $("input[name='VIEW']:checkbox").parent('.normal').removeClass("checked");
         $(this).prop("checked", true);
         $(this).parent('.normal').addClass('checked');
    }
    else{
         $("input[name='VIEW']").prop("checked", false);
         $("input[name='VIEW']").parent('.normal').removeClass('checked');
    }    
});

Http://www.bootply.com/A4h6kAPshx

 0
Author: yardpenalty,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2016-08-29 19:33:35

Cóż, jest łatwiejszy sposób

Najpierw podaj swoje checkboxy przykład klasy 'id_chk'

Następnie wewnątrz pola wyboru, który będzie kontrolował stan pól wyboru 'id_chk':

<input type='checkbox' onchange='js:jQuery(".id_chk").prop("checked", jQuery(this).prop("checked"))' />

To wszystko, mam nadzieję, że to pomoże

 -3
Author: Angel,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/doraprojects.net/template/agent.layouts/content.php on line 54
2013-07-10 16:07:25