Probando si una casilla de verificación está marcada con jQuery


Si la casilla de verificación está marcada, entonces solo necesito obtener el valor como 1; de lo contrario, necesito obtenerlo como 0. ¿Cómo hago esto usando jQuery?

$("#ans").val() siempre me dará un derecho en este caso:

<input type="checkbox" id="ans" value="1" />
Author: TylerH, 2011-01-27

20 answers

Use .is(':checked') para determinar si está o no marcado, y luego establezca su valor en consecuencia.

Más información aquí.

 966
Author: Andy Mikula,
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-03-17 14:38:42
$("#ans").attr('checked') 

Le dirá si está comprobado. También puede usar un segundo parámetro true/false para marcar / desmarcar la casilla de verificación.

$("#ans").attr('checked', true);

Por comentario, use prop en lugar de attr cuando esté disponible. Por ejemplo:

$("#ans").prop('checked')
 203
Author: xaxxon,
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-08-28 20:20:08

Solo use $(selector).is(':checked')

Devuelve un valor booleano.

 85
Author: SimionBaws,
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-05-09 13:13:52
// use ternary operators
$("#ans").is(':checked') ? 1 : 0;
 53
Author: Stefan Brinkmann,
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-04-16 15:31:49

La respuesta de Stefan Brinkmann es excelente, pero incompleta para principiantes (omite la asignación de variables). Solo para aclarar:

// this structure is called a ternary operator
var cbAns = ( $("#ans").is(':checked') ) ? 1 : 0;

Funciona así:

 var myVar = ( if test goes here ) ? 'ans if yes' : 'ans if no' ;

Ejemplo:

var myMath = ( 1 > 2 ) ? 'yes' : 'no' ;
alert( myMath );

Descripciones " no "

Si esto es útil, por favor vote la respuesta de Stefan Brinkmann.

 20
Author: crashwap,
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-30 16:31:56

Puedes probar esto:

$('#studentTypeCheck').is(":checked");
 16
Author: MAnoj Sarnaik,
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-18 14:15:54

He encontrado el mismo problema antes, espero que esta solución pueda ayudarle. primero, agregue un atributo personalizado a sus casillas de verificación:

<input type="checkbox" id="ans" value="1" data-unchecked="0" />

Escribe una extensión jQuery para obtener el valor:

$.fn.realVal = function(){
    var $obj = $(this);
    var val = $obj.val();
    var type = $obj.attr('type');
    if (type && type==='checkbox') {
        var un_val = $obj.attr('data-unchecked');
        if (typeof un_val==='undefined') un_val = '';
        return $obj.prop('checked') ? val : un_val;
    } else {
        return val;
    }
};

Utilice el código para obtener el valor de la casilla de verificación:

$('#ans').realVal();

Puedes probar aquí

 15
Author: alphakevin,
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-07-05 08:22:56
$('input:checkbox:checked').val();        // get the value from a checked checkbox
 7
Author: nobody,
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-08-28 07:42:40

También puedes usar:

$("#ans:checked").length == 1;
 6
Author: Fareed Alnamrouti,
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-06-11 22:44:36
<input type="checkbox" id="ans" value="1" />

Jquery : var test= $("#ans").is(':checked') y devuelve verdadero o falso.

En su función:

$test =($request->get ( 'test' )== "true")? '1' : '0';
 6
Author: Rajesh RK,
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-02-14 04:53:56

Uso:

$("#ans option:selected").val()
 4
Author: Senthil Kumar Bhaskaran,
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-11-03 18:52:19
function chkb(bool){
if(bool)
return 1;
return 0;
}

var statusNum=chkb($("#ans").is(':checked'));

StatusNum será igual a 1 si la casilla de verificación está marcada, y 0 si no lo está.

EDITAR: También puede agregar el DOM a la función.

function chkb(el){
if(el.is(':checked'))
return 1;
return 0;
}

var statusNum=chkb($("#ans"));
 4
Author: kmoney12,
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-12-03 21:14:11

Hay Varias opciones como....

 1. $("#ans").is(':checked') 
 2. $("#ans:checked")
 3. $('input:checkbox:checked'); 

Si todas estas opciones devuelven true, entonces puede establecer el valor de acuerdo.

 3
Author: Amit Maru,
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-07 05:50:49

He pasado por un caso recientemente donde he necesitado comprobar el valor de la casilla de verificación cuando el usuario hizo clic en el botón. La única forma adecuada de hacerlo es usar el atributo prop().

var ansValue = $("#ans").prop('checked') ? $("#ans").val() : 0;

Esto funcionó en mi caso tal vez alguien lo necesite.

Cuando he intentado .attr(':checked') devolvió checked pero quería valor booleano y .val() devolvió el valor del atributo value.

 2
Author: Robert,
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-01-28 12:22:31

Prueba esto

$('input:checkbox:checked').click(function(){
    var val=(this).val(); // it will get value from checked checkbox;
})

Aquí la bandera es verdadera si se marca de otra manera falsa

var flag=$('#ans').attr('checked');

De nuevo esto hará cheked

$('#ans').attr('checked',true);
 1
Author: sharif2008,
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-22 16:19:44

Puede obtener el valor (verdadero / falso) mediante estos dos métodos

$("input[type='checkbox']").prop("checked");
$("input[type='checkbox']").is(":checked");
 0
Author: PPB,
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-08-15 11:31:28

Si desea que el valor entero de marcado o no intente:

$("#ans: checked").longitud

 0
Author: Nasaralla,
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-11-14 12:40:52

Primera comprobación el valor se comprueba

$("#ans").find("checkbox").each(function(){
    if ($(this).prop('checked')==true){ 
    var id = $(this).val()
    }
});

Si no establecer la 0 valor

 0
Author: Ashok Charu,
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-05-07 12:25:56

$('input[id=ans]'). is (': checked');

 0
Author: swathi,
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-27 11:49:47
 $("#id").prop('checked') === true ? 1 : 0;
 0
Author: Paulo Rodrigues,
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-09-25 16:25:03