Obtener el valor de la casilla de verificación en jQuery


¿Cómo puedo obtener el valor de una casilla de verificación en jQuery?

Author: Joel Beckham, 2010-05-14

14 answers

Para obtener el valor del atributo Value puedes hacer algo como esto:

$("input[type='checkbox']").val();

O si ha establecido un class o id para él, puede:

$('#check_id').val();
$('.check_class').val();

Sin embargo, esto devolverá el mismo valor si se comprueba o no, esto puede ser confuso, ya que es diferente al comportamiento del formulario enviado.

Para comprobar si se comprueba o no, haga:

if ($('#check_id').is(":checked"))
{
  // it is checked
}
 757
Author: Sarfraz,
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-02 10:20:06

Esas 2 formas están funcionando:

  • $('#checkbox').prop('checked')
  • $('#checkbox').is(':checked') (gracias @mgsloan )

$('#test').click(function() {
    alert("Checkbox state (method 1) = " + $('#test').prop('checked'));
    alert("Checkbox state (method 2) = " + $('#test').is(':checked'));
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>
Check me: <input id="test" type="checkbox" />
 166
Author: Alain Tiemblo,
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-01-01 22:21:56

Prueba esta pequeña solución:

$("#some_id").attr("checked") ? 1 : 0;

O

$("#some_id").attr("checked") || 0;
 51
Author: RDK,
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-10 09:44:17

Las únicas formas correctas de recuperar el valor de una casilla de verificación son las siguientes

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

Como se explica en las documentaciones oficiales en el sitio web de jQuery. El resto de los métodos no tiene nada que ver con la propiedad de la casilla de verificación, están marcando el atributo lo que significa que están probando el estado inicial de la casilla de verificación cuando se cargó. Así que en resumen:

  • Cuando tiene el elemento y sabe que es una casilla de verificación, simplemente puede leer su propiedad y no lo hará necesita jQuery para eso (es decir, elem.checked) o puede usar $(elem).prop("checked") si desea confiar en jQuery.
  • Si necesita conocer (o comparar) el valor cuando el elemento se cargó por primera vez (es decir, el valor predeterminado), la forma correcta de hacerlo es $(elem).is(":checked").

Las respuestas son engañosas, por favor revise a continuación:

Http://api.jquery.com/prop/

 23
Author: Reza,
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-10-04 07:07:44

Solo para aclarar las cosas:

$('#checkbox_ID').is(":checked")

Devolverá 'verdadero'o' falso '

 13
Author: Greg 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
2015-04-26 21:10:01
$('#checkbox_id').val();
$('#checkbox_id').is(":checked");
$('#checkbox_id:checked').val();
 11
Author: Nalan Madheswaran,
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-07-15 01:25:45
jQuery(".checkboxClass").click(function(){
        var selectedCountry = new Array();
        var n = jQuery(".checkboxClass:checked").length;
        if (n > 0){
            jQuery(".checkboxClass:checked").each(function(){
                selectedCountry.push($(this).val());
            });
        }
        alert(selectedCountry);
    });
 9
Author: Jaskaran singh Rajal,
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-01-09 09:46:51

Simple pero efectivo y asume que sabe que la casilla de verificación se encontrará:

$("#some_id")[0].checked;

Da true/false

 7
Author: Kevin Shea,
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-03-06 10:36:08

A pesar del hecho de que esta pregunta está pidiendo una solución de jQuery, aquí hay una respuesta de JavaScript puro ya que nadie lo ha mencionado.

Sin jQuery:

Simplemente seleccione el elemento y acceda al checked property (que devuelve un booleano).

var checkbox = document.querySelector('input[type="checkbox"]');

alert(checkbox.checked);
<input type="checkbox"/>

Aquí hay un ejemplo rápido escuchando el evento change:

var checkbox = document.querySelector('input[type="checkbox"]');
checkbox.addEventListener('change', function (e) {
    alert(this.checked);
});
<input type="checkbox"/>

Para seleccionar los elementos marcados, utilice el :checked pseudo clase (input[type="checkbox"]:checked).

Aquí hay un ejemplo que itera sobre elementos checked input y devuelve una matriz mapeada de los nombres de los elementos checked.

Ejemplo Aquí

var elements = document.querySelectorAll('input[type="checkbox"]:checked');
var checkedElements = Array.prototype.map.call(elements, function (el, i) {
    return el.name;
});

console.log(checkedElements);

var elements = document.querySelectorAll('input[type="checkbox"]:checked');
var checkedElements = Array.prototype.map.call(elements, function (el, i) {
    return el.name;
});

console.log(checkedElements);
<div class="parent">
    <input type="checkbox" name="name1" />
    <input type="checkbox" name="name2" />
    <input type="checkbox" name="name3" checked="checked" />
    <input type="checkbox" name="name4" checked="checked" />
    <input type="checkbox" name="name5" />
</div>
 6
Author: Josh Crozier,
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-01-15 04:37:28
//By each()
var testval = [];
 $('.hobbies_class:checked').each(function() {
   testval.push($(this).val());
 });


//by map()
var testval = $('input:checkbox:checked.hobbies_class').map(function(){
return this.value; }).get().join(",");

 //HTML Code

 <input type="checkbox" value="cricket" name="hobbies[]"  class="hobbies_class">Cricket 
  <input type="checkbox" value="hockey" name="hobbies[]" class="hobbies_class">Hockey

Ejemplo
Demo

 5
Author: Kamal,
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-19 10:06:19

Aquí es cómo obtener el valor de todas las casillas de verificación marcadas como una matriz:

var values = (function() {
                var a = [];
                $(".checkboxes:checked").each(function() {
                    a.push(this.value);
                });
                return a;
            })()
 1
Author: Faraz Kelhini,
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-05 14:35:13
<script type="text/javascript">
$(document).ready(function(){
    $('.laravel').click(function(){
        var val = $(this).is(":checked");
        $('#category').submit();
    });
});

<form action="{{route('directory')}}" method="post" id="category">
                        <input type="hidden" name="_token" value="{{ csrf_token() }}">
                        <input name="category" value="{{$name->id}}"  class="laravel" type="checkbox">{{$name->name}}
                      </form>
 1
Author: Kuldeep Mishra,
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-08-07 06:34:19

Utilice Esto $('input [name^ = CheckBoxInput]').val();

 1
Author: Myint Thu Lwin,
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-09-25 10:33:05

$('.clase[valor=3]').prop ('checked', true);

 1
Author: Jacksonit.org,
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-07 09:57:09