¿Establecer "marcado" para una casilla de verificación con jQuery?


Me gustaría hacer algo como esto para marcar un checkbox con jQuery:

$(".myCheckBox").checked(true);

O

$(".myCheckBox").selected(true);

¿Existe tal cosa?

Author: Mogsdad, 2009-01-09

30 answers

JQuery 1.6 +

Utilice el nuevo .prop() método:

$('.myCheckbox').prop('checked', true);
$('.myCheckbox').prop('checked', false);

JQuery 1.5.x e inferiores

El método .prop() no está disponible, por lo que debe usar .attr().

$('.myCheckbox').attr('checked', true);
$('.myCheckbox').attr('checked', false);

Tenga en cuenta que este es el enfoque utilizado por las pruebas unitarias de jQuery antes de la versión 1.6 y es preferible a usar

$('.myCheckbox').removeAttr('checked');

Dado que este último, si la casilla se marcó inicialmente, cambiará el comportamiento de una llamada a .reset() en cualquier forma que lo contenga - un cambio de comportamiento sutil pero probablemente no deseado.

Para más contexto, una discusión incompleta de los cambios en el manejo del atributo/propiedad checked en la transición de 1.5.x a 1.6 se puede encontrar en la versión 1.6 notas de la versión y la Atributos vs. Propiedades sección de la .prop() documentación .

Cualquier versión de jQuery

Si está trabajando con un solo elemento, siempre puede modificar el HTMLInputElement's .checked propiedad:

$('.myCheckbox')[0].checked = true;
$('.myCheckbox')[0].checked = false;

El beneficio de usar los métodos .prop() y .attr() en lugar de esto es que operarán en todos los elementos coincidentes.

 5481
Author: Xian,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-04-29 17:27:36

Uso:

$(".myCheckbox").attr('checked', true); // Deprecated
$(".myCheckbox").prop('checked', true);

Y si desea marcar si una casilla de verificación está marcada o no:

$('.myCheckbox').is(':checked');
 637
Author: bchhun,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-03-18 18:34:03

Esta es la forma correcta de marcar y desmarcar las casillas de verificación con jQuery, ya que es estándar multiplataforma, y permitirá repositorios de formularios.

$('.myCheckBox').each(function(){ this.checked = true; });

$('.myCheckBox').each(function(){ this.checked = false; });

Al hacer esto, está utilizando estándares JavaScript para marcar y desmarcar casillas de verificación, por lo que cualquier navegador que implemente correctamente la propiedad "checked" del elemento checkbox ejecutará este código sin problemas. Este debería ser todos los principales navegadores, pero no puedo probar anterior a Internet Explorer 9.

El problema (jQuery 1.6):

Una vez que un usuario hace clic en una casilla de verificación, esa casilla de verificación deja de responder a los cambios de atributo "marcado".

Aquí hay un ejemplo del atributo checkbox que no puede hacer el trabajo después de que alguien haya hecho clic en la casilla de verificación (esto sucede en Chrome).

Fiddle

La Solución:

Usando la propiedad "checked" de JavaScript en los elementos DOM , son capaces de resolver el problema directamente, en lugar de tratar de manipular el DOM para que haga lo que queremos que haga.

Fiddle

Este plugin alterará la propiedad marcada de cualquier elemento seleccionado por jQuery, y marcará y desmarcará correctamente las casillas de verificación en todas las circunstancias. Por lo tanto, si bien esto puede parecer una solución excesiva, mejorará la experiencia del usuario de su sitio y ayudará a evitar la frustración del usuario.

(function( $ ) {
    $.fn.checked = function(value) {
        if(value === true || value === false) {
            // Set the value of the checkbox
            $(this).each(function(){ this.checked = value; });
        } 
        else if(value === undefined || value === 'toggle') {
            // Toggle the checkbox
            $(this).each(function(){ this.checked = !this.checked; });
        }

        return this;
    };
})( jQuery );

Alternativamente, si usted no desea utilizar un plugin, puede utilizar los siguientes fragmentos de código:

// Check
$(':checkbox').prop('checked', true);

// Un-check
$(':checkbox').prop('checked', false);

// Toggle
$(':checkbox').prop('checked', function (i, value) {
    return !value;
});
 288
Author: cwharris,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-07-31 13:43:36

Puedes hacer

$('.myCheckbox').attr('checked',true) //Standards compliant

O

$("form #mycheckbox").attr('checked', true)

Si tiene código personalizado en el evento onclick para la casilla de verificación que desea activar, use este en su lugar:

$("#mycheckbox").click();

Puede desmarcar eliminando el atributo por completo:

$('.myCheckbox').removeAttr('checked')

Puede marcar todas las casillas de verificación como esta:

$(".myCheckbox").each(function(){
    $("#mycheckbox").click()
});
 134
Author: Micah,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-12-29 18:18:24

También puede extender el $.objeto fn con nuevos métodos:

(function($)  {
   $.fn.extend({
      check : function()  {
         return this.filter(":radio, :checkbox").attr("checked", true);
      },
      uncheck : function()  {
         return this.filter(":radio, :checkbox").removeAttr("checked");
      }
   });
}(jQuery));

Entonces puedes hacer:

$(":checkbox").check();
$(":checkbox").uncheck();

O es posible que desee darles más nombres únicos como mycheck() y myuncheck() en caso de que use alguna otra biblioteca que use esos nombres.

 70
Author: livefree75,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2010-08-20 18:19:03
$("#mycheckbox")[0].checked = true;
$("#mycheckbox").attr('checked', true);
$("#mycheckbox").click();

El último activará el evento click para la casilla de verificación, los otros no. Por lo tanto, si tiene código personalizado en el evento onclick para la casilla de verificación que desea activar, use la última.

 61
Author: Chris Brandsma,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2009-02-03 17:06:43

Para marcar una casilla de verificación debe usar

 $('.myCheckbox').attr('checked',true);

O

 $('.myCheckbox').attr('checked','checked');

Y para desmarcar una casilla de verificación siempre debe establecerla en false:

 $('.myCheckbox').attr('checked',false);

Si lo haces

  $('.myCheckbox').removeAttr('checked')

Elimina el atributo todos juntos y, por lo tanto, no podrá restablecer el formulario.

MAL DEMO jQuery 1.6. Creo que esto está roto. Para 1.6 voy a hacer un nuevo post sobre eso.

NUEVO TRABAJO DEMO jQuery 1.5.2 funciona en Chrome.

Ambas demos use

$('#tc').click(function() {
    if ( $('#myCheckbox').attr('checked')) {
        $('#myCheckbox').attr('checked', false);
    } else {
        $('#myCheckbox').attr('checked', 'checked');
    }
});
 58
Author: mcgrailm,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2011-12-29 18:21:55

Suponiendo que la pregunta es...

¿Cómo puedo marcar una casilla de verificación-establecer POR VALOR?

Recuerde que en un conjunto de casillas de verificación típico, todas las etiquetas de entrada tienen el mismo nombre, difieren por el atributo value: no hay ID para cada entrada del conjunto.

La respuesta de Xian se puede extender con un selector más específico , usando la siguiente línea de código:

$("input.myclass[name='myname'][value='the_value']").prop("checked", true);
 42
Author: Peter Krauss,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-06-09 15:07:56

Me falta la solución. Siempre usaré:

if ($('#myCheckBox:checked').val() !== undefined)
{
    //Checked
}
else
{
    //Not checked
}
 42
Author: Overbeeke,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-12-13 16:43:53

Esto selecciona elementos que tienen el atributo especificado con un valor que contiene la subcadena dada "ckbItem":

$('input[name *= ckbItem]').prop('checked', true);

Seleccionará todos los elementos que contengan ckbItem en su atributo name.

 41
Author: Abou-Emish,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2018-07-18 13:44:09

Para marcar una casilla de verificación usando jQuery 1.6 o superior simplemente haga esto:

checkbox.prop('checked', true);

Para desmarcar, use:

checkbox.prop('checked', false);

Esto es lo que me gusta usar para activar una casilla de verificación usando jQuery:

checkbox.prop('checked', !checkbox.prop('checked'));

Si está utilizando jQuery 1.5 o inferior:

checkbox.attr('checked', true);

Para desmarcar, use:

checkbox.attr('checked', false);
 37
Author: Ramon de Jesus,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-09 13:23:02

Aquí hay una manera de hacerlo sin jQuery

function addOrAttachListener(el, type, listener, useCapture) {
  if (el.addEventListener) {
    el.addEventListener(type, listener, useCapture);
  } else if (el.attachEvent) {
    el.attachEvent("on" + type, listener);
  }
};

addOrAttachListener(window, "load", function() {
  var cbElem = document.getElementById("cb");
  var rcbElem = document.getElementById("rcb");
  addOrAttachListener(cbElem, "click", function() {
    rcbElem.checked = cbElem.checked;
  }, false);
}, false);
<label>Click Me!
  <input id="cb" type="checkbox" />
</label>
<label>Reflection:
  <input id="rcb" type="checkbox" />
</label>
 34
Author: Aeoril,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-05-10 09:58:32

Prueba esto:

$('#checkboxid').get(0).checked = true;  //For checking

$('#checkboxid').get(0).checked = false; //For unchecking
 28
Author: prashanth,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-02-16 10:33:47

Aquí está el código para marcado y no marcado con un botón:

var set=1;
var unset=0;
jQuery( function() {
    $( '.checkAll' ).live('click', function() {
        $( '.cb-element' ).each(function () {
            if(set==1){ $( '.cb-element' ).attr('checked', true) unset=0; }
            if(set==0){ $( '.cb-element' ).attr('checked', false); unset=1; }
        });
        set=unset;
    });
});

Actualización: Aquí está el mismo bloque de código usando el método Jquery 1.6+ prop más reciente, que reemplaza a attr:

var set=1;
var unset=0;
jQuery( function() {
    $( '.checkAll' ).live('click', function() {
        $( '.cb-element' ).each(function () {
            if(set==1){ $( '.cb-element' ).prop('checked', true) unset=0; }
            if(set==0){ $( '.cb-element' ).prop('checked', false); unset=1; }
        });
        set=unset;
    });
});
 26
Author: starjahid,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-11 15:55:04

Podemos usar elementObject con jQuery para comprobar el atributo:

$(objectElement).attr('checked');

Podemos usar esto para todas las versiones de jQuery sin ningún error.

Actualización: Jquery 1.6 + tiene el nuevo método prop que reemplaza attr, por ejemplo:

$(objectElement).prop('checked');
 24
Author: Prasanth P,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-04-11 15:53:21

Si está utilizando PhoneGap haciendo desarrollo de aplicaciones, y tiene un valor en el botón que desea mostrar al instante, recuerde hacer esto

$('span.ui-[controlname]',$('[id]')).text("the value");

Encontré que sin el span, la interfaz no se actualizará sin importar lo que hagas.

 23
Author: Clement Ho,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-02-16 10:32:37

Aquí está el código y la demostración de cómo marcar varias casillas de verificación...

Http://jsfiddle.net/tamilmani/z8TTt/

$("#check").on("click", function () {

    var chk = document.getElementById('check').checked;
    var arr = document.getElementsByTagName("input");

    if (chk) {
        for (var i in arr) {
            if (arr[i].name == 'check') arr[i].checked = true;
        }
    } else {
        for (var i in arr) {
            if (arr[i].name == 'check') arr[i].checked = false;
        }
    }
});
 22
Author: tamilmani,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2016-02-10 13:18:22

Otra posible solución:

    var c = $("#checkboxid");
    if (c.is(":checked")) {
         $('#checkboxid').prop('checked', false);
    } else {
         $('#checkboxid').prop('checked', true);
    }
 19
Author: Muhammad Aamir Ali,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-07-21 09:34:50

Si usa el móvil y desea que la interfaz se actualice y muestre la casilla de verificación sin marcar, use lo siguiente:

$("#checkbox1").prop('checked', false).checkboxradio("refresh");
 17
Author: Matt Peacock,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-01-11 13:05:35

Tenga en cuenta las fugas de memoria en Internet Explorer antes de Internet Explorer 9 , como dice la documentación de jQuery :

En Internet Explorer antes de la versión 9, usando .prop () para establecer un DOM propiedad del elemento a cualquier cosa que no sea un valor primitivo simple (number, string, or boolean) puede causar pérdidas de memoria si la propiedad es no eliminado (usando .removeProp()) antes de que se elimine el elemento DOM del documento. Para establecer valores de forma segura en objetos DOM sin memoria fugas, uso .datos().

 17
Author: naor,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-11-22 15:33:52

Para jQuery 1.6 +

$('.myCheckbox').prop('checked', true);
$('.myCheckbox').prop('checked', false);

Para jQuery 1.5.x e inferiores

$('.myCheckbox').attr('checked', true);
$('.myCheckbox').attr('checked', false);

Para comprobar,

$('.myCheckbox').removeAttr('checked');
 17
Author: logan,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-04-21 10:29:07

Para marcar y desmarcar

$('.myCheckbox').prop('checked', true);
$('.myCheckbox').prop('checked', false);
 16
Author: jj2422,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-12-03 02:18:05
$('controlCheckBox').click(function(){
    var temp = $(this).prop('checked');
    $('controlledCheckBoxes').prop('checked', temp);
});
 15
Author: mahmoh,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-07-16 02:57:18

Esta es probablemente la solución más corta y fácil:

$(".myCheckBox")[0].checked = true;

O

$(".myCheckBox")[0].checked = false;

Aún más corto sería:

$(".myCheckBox")[0].checked = !0;
$(".myCheckBox")[0].checked = !1;

Aquí está a jsFiddle también.

 14
Author: frieder,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-12-13 16:46:09

Como @ livefree75 dijo:

JQuery 1.5.x e inferior

También puede extender el $.objeto fn con nuevos métodos:

(function($)  {
   $.fn.extend({
      check : function()  {
         return this.filter(":radio, :checkbox").attr("checked", true);
      },
      uncheck : function()  {
         return this.filter(":radio, :checkbox").removeAttr("checked");
      }
   });
}(jQuery));

Pero en las nuevas versiones de jQuery, tenemos que usar algo como esto:

JQuery 1.6+

    (function($)  {
       $.fn.extend({
          check : function()  {
             return this.filter(":radio, :checkbox").prop("checked", true);
          },
          uncheck : function()  {
             return this.filter(":radio, :checkbox").prop("checked",false);
          }
       });
    }(jQuery));

Entonces puedes hacer:

    $(":checkbox").check();
    $(":checkbox").uncheck();
 14
Author: Ardalan Shahgholi,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2017-05-21 11:00:42

JavaScript simple es muy simple y mucho menos sobrecarga:

var elements = document.getElementsByClassName('myCheckBox');
for(var i = 0; i < elements.length; i++)
{
    elements[i].checked = true;
}

Ejemplo aquí

 13
Author: Alex W,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-09-23 01:12:17

Cuando marcó una casilla de verificación como;

$('.className').attr('checked', 'checked')

Podría no ser suficiente. También debe llamar a la función de abajo;

$('.className').prop('checked', 'true')

Especialmente cuando eliminó el atributo checkbox checked.

 12
Author: Serhat Koroglu,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2015-03-05 13:10:51

No pude hacerlo funcionar usando:

$("#cb").prop('checked', 'true');
$("#cb").prop('checked', 'false');

Tanto true como false marcarían la casilla de verificación. Lo que funcionó para mí fue:

$("#cb").prop('checked', 'true'); // For checking
$("#cb").prop('checked', '');     // For unchecking
 11
Author: fredcrs,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-12-15 18:44:58

Aquí está la respuesta completa usando jQuery

Lo pruebo y funciona al 100%: D

    // when the button (select_unit_button) is clicked it returns all the checed checkboxes values 
    $("#select_unit_button").on("click", function(e){

             var arr = [];

             $(':checkbox:checked').each(function(i){
                 arr[i] = $(this).val(); // u can get id or anything else
             });

              //console.log(arr); // u can test it using this in google chrome
    });
 10
Author: ,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2013-02-27 15:49:10

En jQuery,

if($("#checkboxId").is(':checked')){
    alert("Checked");
}

O

if($("#checkboxId").attr('checked')==true){
    alert("Checked");
}

En JavaScript,

if (document.getElementById("checkboxID").checked){
    alert("Checked");
}
 10
Author: ijarlax,
Warning: date(): Invalid date.timezone value 'Europe/Kyiv', we selected the timezone 'UTC' for now. in /var/www/agent_stack/data/www/ajaxhispano.com/template/agent.layouts/content.php on line 61
2014-04-03 21:31:55