Cómo recuperar valores de casillas de verificación en jQuery


¿Cómo usar jQuery para obtener los valores de las casillas de verificación marcadas y colocarlo en un área de texto inmediatamente?

Justo como este código:

<html>
  <head>
  </head>

  <body>
    <div id="c_b">
      <input type="checkbox" value="one_name" checked>
      <input type="checkbox" value="one_name1">
      <input type="checkbox" value="one_name2">
    </div>  

    <textarea id="t"></textarea>
  </body>
</html>

Si el id="c_d" es actualizado por Ajax, lo siguiente del código de altCognito no funciona. Hay alguna buena solución?

Author: user86745458, 2009-04-24

16 answers

Aquí hay uno que funciona ( ver el ejemplo):

 function updateTextArea() {         
     var allVals = [];
     $('#c_b :checked').each(function() {
       allVals.push($(this).val());
     });
     $('#t').val(allVals);
  }
 $(function() {
   $('#c_b input').click(updateTextArea);
   updateTextArea();
 });

Actualización

Algunos meses después se hizo otra pregunta con respecto a cómo mantener el trabajo anterior si el ID cambia. Bueno, la solución se reduce a mapear la función updateTextArea en algo genérico que usa clases CSS, y usar la función live para monitorear el DOM en busca de esos cambios.

 306
Author: cgp,
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-11-14 15:44:27

También puede devolver todos los valores de las casillas de verificación seleccionadas en una cadena separada por comas. Esto también lo hará más fácil para usted cuando lo envíe como un parámetro a SQL

Aquí hay un ejemplo que devuelve todos los valores de las casillas de verificación seleccionadas que tienen el nombre "chkboxName" en una cadena separada por comas

Y aquí está el javascript

function showSelectedValues()
{
  alert($("input[name=chkboxName]:checked").map(
     function () {return this.value;}).get().join(","));
}

Aquí está la muestra HTML

<html>
  <head>
 </head>
 <body>
  <div>
   <input name="chkboxName" type="checkbox" value="one_name" checked>
   <input name="chkboxName" type="checkbox" value="one_name1">
   <input name="chkboxName" type="checkbox" value="one_name2">
  </div>  
 </body>
 </html>
 115
Author: Mohamed ElSheikh,
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-24 20:42:42

Su pregunta es bastante vaga, pero creo que esto es lo que necesita:

$(function() { 
    $('input[type="checkbox"]').bind('click',function() {
        if($(this).is(':checked')) {
            $('#some_textarea').html($(this).val());
         }
   });
});

Editar: Oh, está bien.. ahí lo tienes... No tenías el HTML antes. De todos modos, sí, pensé que querías poner el valor en un área de texto cuando se hace clic. Si desea que los valores de las casillas de verificación marcadas se pongan en el área de texto (tal vez con una buena separación por coma) al cargar la página, sería tan simple como:

$(function() { 
    $('#c_b input[type="checkbox"]:checked').each(function() { 
        $('#t').append(', '+$(this).val());
    });
});

Edit 2 Como la gente ha hecho, también puede hacer esto para abreviar el largo selector escribí:

$('#c_b :checkbox:checked').each(function() {
    $('#t').append(', '+$(this).val());
});

... Me olvidé por completo de ese atajo. ;)

 62
Author: KyleFarris,
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-04-24 15:12:12

Esto funciona perfectamente para mí:

alert($("input[name=chkboxName]:checked").map(function() {
    return this.value;
}).get().join(","));

Gracias Mohamed elSheikh

 43
Author: Nic,
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-12 15:04:20

Gracias altCognito, su solución ayudó. También podemos hacer esto usando el nombre de las casillas de verificación:

function updateTextArea() {         
   var allVals = [];
   $('[name=chkbox]:checked').each(function() {
      allVals.push($(this).val());
   });
   $('#t').val(allVals)
} 
$(function() { 
    $('#c_b input').click(updateTextArea);
    updateTextArea();
});
 8
Author: Harpreet Bhatia,
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-11-14 17:52:04

Lo siguiente puede ser útil ya que llegué aquí buscando una solución ligeramente diferente. Mi script necesitaba recorrer automáticamente los elementos de entrada y tenía que devolver sus valores (para jQuery.post () function), el problema era que las casillas de verificación devolvían sus valores independientemente del estado marcado. Esta fue mi solución:

jQuery.fn.input_val = function(){

    if(jQuery(this).is("input[type=checkbox]")) {
        if(jQuery(this).is(":checked")) {
            return jQuery(this).val();
        } else {
            return false;
        }
    } else {
        return jQuery(this).val();
    }
};

Uso:

jQuery(".element").input_val();

Si el campo de entrada dado es una casilla de verificación, la función input_val solo devuelve un valor si está marcada. Para todos los demás elementos, el el valor se devuelve independientemente del estado marcado.

 6
Author: Andy,
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-12-28 05:00:41

Aquí hay una alternativa en caso de que necesite guardar el valor en una variable:

var _t = $('#c_b :checkbox:checked').map(function() {
    return $(this).val();
});
$('#t').append(_t.join(','));

(map () devuelve un array, que encuentro más práctico que el texto en textarea).

 5
Author: pgcd,
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-12 15:03:05
   $(document).ready(function() {
        $(':checkbox').click(function(){
           var cObj = $(this);
           var cVal = cObj.val();
           var tObj = $('#t');
           var tVal = tObj.val();
           if( cObj.attr("checked")) {
              tVal = tVal + "," + cVal; 
              $('#t').attr("value", tVal);
           } else {
              //TODO remove unchecked value.
           }
        });
    });
 3
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
2009-04-24 15:10:50
 function updateTextArea() {         
     var allVals = $('#c_b :checked').map(function() {
       return $(this).val();
     }).get();
     $('#t').val(allVals)
  }
 $(function() {
   $('#c_b input').click(updateTextArea);
   updateTextArea();
 });
 3
Author: satoru,
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-04 07:03:25
$("#t").text($("#cb").find(":checked").val())
 2
Author: mkoryak,
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-04-24 14:51:13

De todos modos, probablemente necesites algo como esto:

 var val = $('#c_b :checkbox').is(':checked').val();
 $('#t').val( val );

Esto obtendrá el valor de la primera casilla de verificación marcada en la página e insertará eso en el área de texto con id='textarea'.

Tenga en cuenta que en su código de ejemplo debe poner las casillas de verificación en un formulario.

 2
Author: Pim Jager,
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-02-04 19:16:38

Una forma mucho más fácil y corta que estoy usando para lograr lo mismo, usando la respuesta de otro post, es así:

var checkedCities = $('input[name=city]:checked').map(function() {
    return this.value;
}).get();

Originalmente las ciudades se recuperan de una base de datos MySQL, y se colocan en bucle en PHP while loop:

while ($data = mysql_fetch_assoc($all_cities)) {
<input class="city" name="city" id="<?php echo $data['city_name']; ?>" type="checkbox" value="<?php echo $data['city_id']; ?>" /><?php echo $data['city_name']; ?><br />
<?php } ?>

Ahora, usando el código jQuery anterior, obtengo todos los valores city_id, y envío de nuevo a la base de datos usando $.conseguir(...)

Esto ha hecho mi vida tan fácil ya que ahora el código es totalmente dinámico. Para agregar más ciudades, todo lo que necesito hacer es agregar más ciudades en mi base de datos, y no se preocupe en PHP o jQuery final.

 2
Author: zeeshan,
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-12 15:03:42
<html>
<head>
<title>jQuery check / uncheck a check box example</title>

<script type="text/javascript" src="jquery-1.3.2.min.js"></script>

</head>

<body>

<h1>jQuery check / uncheck a check box example</h1>

<script type="text/javascript">

  $(document).ready(function(){

    $("#isCheck").click(function () {

    alert($('input:checkbox[name=checkme]').is(':checked'));

    });

    $("#checkIt").click(function () {

    $('input:checkbox[name=checkme]').attr('checked',true);

    });

    $("#UnCheckIt").click(function () {

    $('input:checkbox[name=checkme]').attr('checked',false);

    }); 

  });
</script>
</head><body>

<input type="checkbox" name="checkme">Check Me</input>

<br/>
<br/>
<br/>

<input type='button' value='Is Check' id='isCheck'>
<input type='button' value='Check It' id='checkIt'>
<input type='button' value='UnCheck It' id='UnCheckIt'>

</body>
</html>
 1
Author: sarath,
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-03 11:14:32

He tenido un problema similar y así es como lo resolví usando los ejemplos anteriores:

 $(".ms-drop").click(function () {
        $(function showSelectedValues() {
            alert($(".ms-drop input[type=checkbox]:checked").map(
               function () { return this.value; }).get().join(","));
        });
    });
 0
Author: sam,
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-11-05 20:00:44

Prueba este..

var listCheck = [];
console.log($("input[name='YourCheckBokName[]']"));
$("input[name='YourCheckBokName[]']:checked").each(function() {
     console.log($(this).val());
     listCheck .push($(this).val());
});
console.log(listCheck);
 0
Author: sonida,
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-17 19:13:27

Si desea insertar el valor de cualquier casilla de verificación inmediatamente mientras se está marcando, esto debería funcionar para usted:

$(":checkbox").click(function(){
  $("#id").text(this.value)
})
 0
Author: duckyflip,
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-19 01:21:52