Usar jquery para obtener todas las casillas de verificación marcadas con un nombre de clase determinado


Sé que puedo obtener todas las casillas de verificación marcadas en una página usando esto:

$('input[type=checkbox]').each(function () {
    var sThisVal = (this.checked ? $(this).val() : "");
});

Pero ahora estoy usando esto en una página que tiene algunas otras casillas de verificación que no quiero incluir. ¿Cómo cambiaría el código anterior para ver solo las casillas de verificación marcadas que tienen una cierta clase en ellas?

Author: peter-b, 2011-03-27

12 answers

$('.theClass:checkbox:checked') le dará todas las casillas marcadas con la clase theClass.

 280
Author: Cokegod,
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-08 22:47:02
$('input:checkbox.class').each(function () {
       var sThisVal = (this.checked ? $(this).val() : "");
  });

Un ejemplo para demostrar.

:checkbox es un selector para casillas de verificación (de hecho, podría omitir la parte input del selector, aunque encontré casos de nicho donde obtendría resultados extraños haciendo esto en versiones anteriores de la biblioteca. Estoy seguro de que se arreglan en versiones posteriores). .class es el selector para el atributo de clase de elemento que contiene class.

 103
Author: Russ Cam,
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-03-27 15:20:34

Obligatorio .map ejemplo:

var checkedVals = $('.theClass:checkbox:checked').map(function() {
    return this.value;
}).get();
alert(checkedVals.join(","));
 60
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
2011-03-27 15:27:45
$('input.yourClass:checkbox:checked').each(function () {
    var sThisVal = $(this).val();
});

Esto obtendría todas las casillas de verificación del nombre de clase "YourClass". Me gusta este ejemplo, ya que utiliza el selector jQuery checked en lugar de hacer una comprobación condicional. Personalmente, también usaría una matriz para almacenar el valor, luego los usaría según sea necesario, como:

var arr = [];
$('input.yourClass:checkbox:checked').each(function () {
    arr.push($(this).val());
});
 16
Author: alienriver49,
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-07-28 14:33:27

Si necesita obtener el valor de todas las casillas de verificación marcadas como una matriz:

let myArray = (function() {
    let a = [];
    $(".checkboxes:checked").each(function() {
        a.push(this.value);
    });
    return a;
})()
 10
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
2018-05-20 11:17:45
 $('input.myclass[type=checkbox]').each(function () {
   var sThisVal = (this.checked ? $(this).val() : ""); });

Ver Selectores de clase jQuery.

 7
Author: Liza Daly,
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-03-27 15:15:46

No estoy seguro de si ayuda para su caso particular, y no estoy seguro de si en su caso, las casillas de verificación que desea incluir solo son parte de un solo formulario o div o tabla, pero siempre puede seleccionar todas las casillas de verificación dentro de un elemento específico. Por ejemplo:

<ul id="selective">
 <li><input type="checkbox" value="..." /></li>
 <li><input type="checkbox" value="..." /></li>
 <li><input type="checkbox" value="..." /></li>
 <li><input type="checkbox" value="..." /></li>
</ul>

Luego, usando el siguiente jQuery, solo pasa por las casillas de verificación dentro de esa UL con id = "selectivo":

$('#selective input:checkbox').each(function () {
 var sThisVal = (this.checked ? $(this).val() : "");
});
 7
Author: Florian Mertens,
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-10 16:28:17
 $('input.theclass[type=checkbox]').each(function () {
   var sThisVal = (this.checked ? $(this).val() : "");
 });
 6
Author: Alp,
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-03-27 15:15:10
<input type="checkbox" id="Checkbox1" class = "chk" value = "1" />
<input type="checkbox" id="Checkbox2" class = "chk" value = "2" />
<input type="checkbox" id="Checkbox3" class = "chk" value = "3" />
<input type="checkbox" id="Checkbox4" class = "chk" value = "4" />
<input type="button" id="demo" value = "Demo" />

<script type = "text/javascript" src = "http://ajax.aspnetcdn.com/ajax/jQuery/jquery-1.6.1.min.js"></script>
<script type="text/javascript">
    $("#demo").live("click", function () {
        $("input:checkbox[class=chk]:checked").each(function () {
            alert("Id: " + $(this).attr("id") + " Value: " + $(this).val());
        });
    });
</script>

Http://www.jqueryfaqs.com/Articles/Get-values-of-all-checked-checkboxes-by-class-name-using-jQuery.aspx

 4
Author: Debendra Dash,
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-01-03 06:39:04

Sé que esto tiene un montón de grandes respuestas a esta pregunta ya, pero encontré esto mientras navegaba y me parece muy fácil de usar. Pensé en compartirlo con cualquiera que lo busque.

HTML:

<fieldset>
    <!-- these will be affected by check all -->
    <div><input type="checkbox" class="checkall"> Check all</div>
    <div><input type="checkbox"> Checkbox</div>
    <div><input type="checkbox"> Checkbox</div>
    <div><input type="checkbox"> Checkbox</div>
</fieldset>
<fieldset>
    <!-- these won't be affected by check all; different field set -->
    <div><input type="checkbox"> Checkbox</div>
    <div><input type="checkbox"> Checkbox</div>
    <div><input type="checkbox"> Checkbox</div>
</fieldset>

JQuery:

$(function () {
    $('.checkall').on('click', function () {
        $(this).closest('fieldset').find(':checkbox').prop('checked', this.checked);
    });
});

Referencia: Lo más fácil es "Comprobar todo" con jQuery

 3
Author: Tony,
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-29 14:25:17

Puedes usar algo como esto:
HTML:

<div><input class="yourClass" type="checkbox" value="1" checked></div>
<div><input class="yourClass" type="checkbox" value="2"></div>
<div><input class="yourClass" type="checkbox" value="3" checked></div>
<div><input class="yourClass" type="checkbox" value="4"></div>


JQuery:

$(".yourClass:checkbox").filter(":checked")


Elegirá valores de 1 y 3.

 3
Author: Philip Voloshin,
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-24 15:48:36

Forma sencilla de obtener todos los valores en una matriz

var valores = (function () {
    var valor = [];
    $('input.className[type=checkbox]').each(function () {
        if (this.checked)
            valor.push($(this).val());
    });
    return valor;

})();

console.log(valores);
 2
Author: Caike Bispo,
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-24 15:53:12