¿Cómo comprobar si una casilla de verificación está marcada en jQuery?


Necesito marcar la propiedad checked de una casilla de verificación y realizar una acción basada en la propiedad marcada usando jQuery.

Por ejemplo, si la casilla edad está marcada, entonces necesito mostrar un cuadro de texto para ingresar la edad, de lo contrario ocultar el cuadro de texto.

Pero el siguiente código devuelve false por defecto:

if ($('#isAgeSelected').attr('checked'))
{
    $("#txtAge").show();
}
else
{
    $("#txtAge").hide();
}

¿Cómo puedo consultar correctamente la propiedad checked?

Author: Prasad, 2009-05-23

30 answers

¿Cómo puedo consultar correctamente la propiedad marcada?

La propiedad checked de un elemento checkbox DOM le dará el estado checked del elemento.

Dado tu código existente, podrías hacer esto:

if(document.getElementById('isAgeSelected').checked) {
    $("#txtAge").show();
} else {
    $("#txtAge").hide();
}

Sin embargo, hay una manera mucho más bonita de hacer esto, usando toggle:

$('#isAgeSelected').click(function() {
    $("#txtAge").toggle(this.checked);
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<input type="checkbox" id="isAgeSelected"/>
<div id="txtAge" style="display:none">Age is something</div>
 3137
Author: karim79,
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-03-09 02:06:27

Use la función is() de jQuery:

if($("#isAgeSelected").is(':checked'))
    $("#txtAge").show();  // checked
else
    $("#txtAge").hide();  // unchecked
 1579
Author: Bhanu Krishnan,
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
2012-08-23 03:42:16

Usando jQuery > 1.6

<input type="checkbox" value="1" name="checkMeOut" id="checkMeOut" checked="checked" />

// traditional attr
$('#checkMeOut').attr('checked'); // "checked"
// new property method
$('#checkMeOut').prop('checked'); // true

Usando el nuevo método de propiedad:

if($('#checkMeOut').prop('checked')) {
    // something when checked
} else {
    // something else when not
}
 481
Author: SeanDowney,
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-06-23 17:29:18

JQuery 1.6+

$('#isAgeSelected').prop('checked')

JQuery 1.5 y versiones anteriores

$('#isAgeSelected').attr('checked')

Cualquier versión de jQuery

// Assuming an event handler on a checkbox
if (this.checked)

Todo el crédito va a Xian.

 185
Author: ungalcrys,
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-23 12:26:29

Estoy usando esto y esto está funcionando absolutamente bien:

$("#checkkBoxId").attr("checked") ? alert("Checked") : alert("Unchecked");

Nota: Si la casilla de verificación está marcada, devolverá true de lo contrario indefinido, así que mejor verifique el valor "TRUE".

 149
Author: Pradeep,
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-05-07 12:18:22

Uso:

<input type="checkbox" name="planned_checked" checked id="planned_checked"> Planned

$("#planned_checked").change(function() {
    if($(this).prop('checked')) {
        alert("Checked Box Selected");
    } else {
        alert("Checked Box deselect");
    }
});

    $("#planned_checked").change(function() {
        if($(this).prop('checked')) {
            alert("Checked Box Selected");
        } else {
            alert("Checked Box deselect");
        }
    });
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
<input type="checkbox" name="planned_checked" checked id="planned_checked"> Planned
 122
Author: Lalji Dhameliya,
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-06-15 07:16:33

Desde jQuery 1.6, el comportamiento de jQuery.attr() ha cambiado y se recomienda a los usuarios que no lo usen para recuperar el estado marcado de un elemento. En su lugar, debe usar jQuery.prop():

$("#txtAge").toggle(
    $("#isAgeSelected").prop("checked") // For checked attribute it returns true/false;
                                        // Return value changes with checkbox state
);

Otras Dos posibilidades son:

$("#txtAge").get(0).checked
$("#txtAge").is(":checked")
 108
Author: Salman A,
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-10-30 17:10:20

Esto funcionó para mí:

$get("isAgeSelected ").checked == true

Donde isAgeSelected es el id del control.

Además, la respuesta de @karim79 funciona bien. No estoy seguro de lo que me perdí en el momento en que lo probé.

Nota, esta es la respuesta utiliza Microsoft Ajax, no jQuery

 84
Author: Prasad,
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-23 12:34:51

Si está utilizando una versión actualizada de jquery, debe ir a .prop método para resolver su problema:

$('#isAgeSelected').prop('checked') devolverá true si está marcado y false si no está marcado. Lo confirmé y me encontré con este problema antes. $('#isAgeSelected').attr('checked') y $('#isAgeSelected').is('checked') está regresando undefined que no es una respuesta digna para la situación. Así que haz lo que se indica a continuación.

if($('#isAgeSelected').prop('checked')) {
    $("#txtAge").show();
} else {
    $("#txtAge").hide();
}

Espero que ayude :)- Gracias.

 81
Author: Rajesh Omanakuttan,
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-09-12 16:10:02

Usar el controlador de eventos Click para la propiedad checkbox no es confiable, ya que la propiedad checked puede cambiar durante la ejecución del controlador de eventos.

Lo ideal sería poner su código en un controlador de eventos change tal como se activa cada vez que se cambia el valor de la casilla de verificación (independientemente de cómo se hace).

$('#isAgeSelected').bind('change', function () {

   if ($(this).is(':checked'))
     $("#txtAge").show();
   else
     $("#txtAge").hide();
});
 55
Author: arviman,
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-10-30 17:09:33

Decidí publicar una respuesta sobre cómo hacer exactamente lo mismo sin jQuery. Sólo porque soy un rebelde.

var ageCheckbox = document.getElementById('isAgeSelected');
var ageInput = document.getElementById('txtAge');

// Just because of IE <333
ageCheckbox.onchange = function() {
    // Check if the checkbox is checked, and show/hide the text field.
    ageInput.hidden = this.checked ? false : true;
};

Primero obtienes ambos elementos por su ID. Luego asigna el evento onchange del checkboxe a una función que comprueba si la casilla de verificación se ha marcado y establece la propiedad hidden del campo de texto age apropiadamente. En ese ejemplo usando el operador ternario.

Aquí hay un violín para que lo pruebes.

Adición

Si la compatibilidad entre navegadores es un problema, entonces propongo establecer la propiedad CSS display en none y inline.

elem.style.display = this.checked ? 'inline' : 'none';

Más lento pero compatible con varios navegadores.

 50
Author: Octavian Damiean,
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
2012-04-05 15:50:25

Creo que podrías hacer esto:

if ($('#isAgeSelected :checked').size() > 0)
{
    $("#txtAge").show(); 
} else { 
    $("#txtAge").hide();
}
 40
Author: xenon,
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-05-23 15:34:24

Hay muchas maneras de comprobar si una casilla de verificación está marcada o no:

Forma de comprobar usando jQuery

if (elem.checked)
if ($(elem).prop("checked"))
if ($(elem).is(":checked"))
if ($(elem).attr('checked'))

Compruebe ejemplo o también documento:

 39
Author: Parth Chavda,
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-10-30 17:30:42

Me encontré exactamente con el mismo problema. Tengo un ASP.NET casilla

<asp:CheckBox ID="chkBox1" CssClass='cssChkBox1' runat="server" />

En el código jQuery utilicé el siguiente selector para verificar si la casilla de verificación estaba marcada o no, y parece funcionar como un encanto.

if ($("'.cssChkBox1 input[type=checkbox]'").is(':checked'))
{ ... } else { ... }

Estoy seguro de que también puede utilizar el ID en lugar de la CssClass,

if ($("'#cssChkBox1 input[type=checkbox]'").is(':checked'))
{ ... } else { ... }

Espero que esto te ayude.

 38
Author: Nertim,
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-05-25 10:59:04

Esto funciona para mí:

/* isAgeSelected being id for checkbox */

$("#isAgeSelected").click(function(){
  $(this).is(':checked') ? $("#txtAge").show() : $("#txtAge").hide();
});
 36
Author: ashish amatya,
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-10-30 17:08:46

Este es un método diferente para hacer lo mismo:

$(document).ready(function (){

    $('#isAgeSelected').click(function() {
        // $("#txtAge").toggle(this.checked);

        // Using a pure CSS selector
        if ($(this.checked)) {
            alert('on check 1');
        };

        // Using jQuery's is() method
        if ($(this).is(':checked')) {
            alert('on checked 2');
        };

        //  // Using jQuery's filter() method
        if ($(this).filter(':checked')) {
            alert('on checked 3');
        };
    });
});
<script src="http://code.jquery.com/jquery-1.9.1.js"></script>
<input type="checkbox" id="isAgeSelected"/>
<div id="txtAge" style="display:none">Age is something</div>
 33
Author: Sangeet Shah,
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-10-30 17:34:28

Usa esto:

if ($('input[name="salary_in.Basic"]:checked').length > 0)

La longitud es mayor que cero si la casilla de verificación está marcada.

 32
Author: Hamid N K,
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-01-16 08:51:06

Puedes usar este código:

$('#isAgeSelected').click(function(){
   console.log(this.checked);
   if(this.checked == true) {
        $("#txtAge").show();
    } else {
       $("#txtAge").hide();
   }
});
 31
Author: sandeep kumar,
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-10-30 17:36:57
$(selector).attr('checked') !== undefined

Esto devuelve true si la entrada está marcada y false si no lo está.

 30
Author: fe_lix_,
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-03-21 11:13:00
$(document).ready(function() {    
    $('#agecheckbox').click(function() {
        if($(this).is(":checked"))
        {
            $('#agetextbox').show();
        } else {
            $('#agetextbox').hide();
        }
    });
});
 30
Author: Jumper Pot,
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-26 15:07:01

Mi manera de hacer esto es:

if ( $("#checkbox:checked").length ) {       
    alert("checkbox is checked");
} else {
    alert("checkbox is not checked");
}
 30
Author: Dalius I,
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-06 20:52:33

Puedes usar:

  if(document.getElementById('isAgeSelected').checked)
    $("#txtAge").show();  
  else
    $("#txtAge").hide();

if($("#isAgeSelected").is(':checked'))
  $("#txtAge").show();  
else
  $("#txtAge").hide();

Ambos deberían funcionar.

 28
Author: Muhammad Awais,
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-09-21 15:21:33

Este ejemplo es para button.

Intente lo siguiente:

<input type="button" class="check" id="checkall" value="Check All" />  &nbsp; <input type="button" id="remove" value="Delete" /> <br/>

<input type="checkbox" class="cb-element"  value="1" /> Checkbox  1 <br/>
<input type="checkbox" class="cb-element"  value="2" /> Checkbox  2 <br/>
<input type="checkbox" class="cb-element"  value="3" /> Checkbox  3 <br/>


$('#remove').attr('disabled', 'disabled'); 

$(document).ready(function() {  

    $('.cb-element').click(function() {

        if($(this).prop('checked'))
        {
            $('#remove').attr('disabled', false);
        }
        else
        {
            $('#remove').attr('disabled', true);
        }
    });   

    $('.check:button').click(function()
{
    var checked = !$(this).data('checked');
    $('input:checkbox').prop('checked', checked);
    $(this).data('checked', checked);

    if(checked == true)
    {
        $(this).val('Uncheck All');
         $('#remove').attr('disabled', false);
    }

    else if(checked == false)
    {
        $(this).val('Check All');
        $('#remove').attr('disabled', true);
    }
});
});
 24
Author: usayee,
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-06-02 14:17:27

La respuesta principal no lo hizo por mí. Esto hizo sin embargo:

<script type="text/javascript">
    $(document).ready(function(){

        $("#li_13").click(function(){
            if($("#agree").attr('checked')){
                $("#saveForm").fadeIn();
            }
            else
            {
                $("#saveForm").fadeOut();
            }
        });
    });
</script>

Básicamente cuando se hace clic en el elemento #li_13, comprueba si el elemento # agree (que es la casilla de verificación) está marcado mediante la función .attr('checked'). Si es entonces fadeIn el elemento # saveForm, y si no fadeOut el elemento saveForm.

 23
Author: BigHomie,
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-10-30 17:12:04

1) Si su marcado HTML es:

<input type="checkbox"  />

Attr usado:

$(element).attr("checked"); // Will give you undefined as initial value of checkbox is not set

Si se usa prop:

$(element).prop("checked"); // Will give you false whether or not initial value is set

2) Si su marcado HTML es:

 <input type="checkbox"  checked="checked" />// May be like this also  checked="true"

Attr usado:

$(element).attr("checked") // Will return checked whether it is checked="true"

Apoyo utilizado:

$(element).prop("checked") // Will return true whether checked="checked"
 23
Author: Somnath Kharat,
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-10-30 17:25:33

Alternar: 0/1 o bien

<input type="checkbox" id="nolunch" />
<input id="checklunch />"

    $('#nolunch').change(function () {
    if ($(this).is(':checked')) {
        $('#checklunch').val('1');
    };
    if ($(this).is(':checked') == false) {
        $('#checklunch').val('0');
    };
});
 21
Author: user2385302,
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-05-05 08:48:08

Estoy usando esto:

 <input type="checkbox" id="isAgeSelected" value="1" /> <br/>
 <input type="textbox" id="txtAge" />

 $("#isAgeSelected").is(':checked') ? $("#txtAge").show() : $("#txtAge").hide();
 19
Author: Nishant,
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-10-30 17:22:27

Aunque ha propuesto una solución JavaScript para su problema (mostrando un textbox cuando un checkbox es checked), este problema podría resolverse solo con css. Con este enfoque, su formulario funciona para los usuarios que han deshabilitado JavaScript.

Asumiendo que tienes el siguiente HTML:

<label for="show_textbox">Show Textbox</label>
<input id="show_textbox" type="checkbox" />
<input type="text" />

Puede usar el siguiente CSS para lograr la funcionalidad deseada:

 #show_textbox:not(:checked) + input[type=text] {display:none;}

Para otros escenarios, puede pensar en selectores CSS apropiados.

Aquí está un Fiddle to demonstrate this approach .

 19
Author: Ormoz,
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-10-30 17:32:58
if($("#checkkBoxId").is(':checked')){
  alert("Checked=true");
}

O

if($("#checkkBoxId").attr('checked') == true){
  alert("checked=true");
}
 16
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
2013-06-10 13:12:59

Creo que será el simple

$('#isAgeSelected').change(function() {
    if($(this).is(":checked")) {
        $('#txtAge').show();
    }
else{
        $('#txtAge').hide();
    }                                          
});
 15
Author: Jitendra Damor,
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-06-04 05:07:16