Obtener el valor de la casilla de verificación marcada?


Así que tengo un código que se ve así:

<input class="messageCheckbox" type="checkbox" value="3" name="mailId[]">
<input class="messageCheckbox" type="checkbox" value="1" name="mailId[]">

Solo necesito Javascript para obtener el valor de cualquier casilla de verificación que esté marcada actualmente.

EDITAR : Para agregar, solo habrá UNA casilla marcada.

Author: Richard Barker, 2012-07-22

9 answers

Para los navegadores modernos:

var checkedValue = document.querySelector('.messageCheckbox:checked').value;

Usando jQuery:

var checkedValue = $('.messageCheckbox:checked').val();

javascript Puro, sin jQuery:

var checkedValue = null; 
var inputElements = document.getElementsByClassName('messageCheckbox');
for(var i=0; inputElements[i]; ++i){
      if(inputElements[i].checked){
           checkedValue = inputElements[i].value;
           break;
      }
}
 187
Author: Engineer,
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-26 10:49:49

Nada de lo anterior funcionó para mí, pero simplemente use esto:

document.querySelector('.messageCheckbox').checked;

Feliz codificación.

 191
Author: JanBorup,
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-08 19:25:31

Estoy usando esto en mi código.Prueba esto

var x=$("#checkbox").is(":checked");

Si la casilla de verificación está marcada x será true de lo contrario será false.

 96
Author: user1683014,
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-09-02 13:21:56

En javascript simple:

function test() {
    var cboxes = document.getElementsByName('mailId[]');
    var len = cboxes.length;
    for (var i=0; i<len; i++) {
        alert(i + (cboxes[i].checked?' checked ':' unchecked ') + cboxes[i].value);
    }
}
function selectOnlyOne(current_clicked) {
    var cboxes = document.getElementsByName('mailId[]');
    var len = cboxes.length;
    for (var i=0; i<len; i++) {
        cboxes[i].checked = (cboxes[i] == current);
    }
}
 9
Author: Stano,
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-22 11:10:19

Esto no responde directamente a la pregunta, pero puede ayudar a los futuros visitantes.


Si desea que una variable sea siempre el estado actual de la casilla de verificación (en lugar de tener que seguir comprobando su estado), puede modificar el evento onchange para establecer esa variable.

Esto se puede hacer en el HTML:

<input class='messageCheckbox' type='checkbox' onchange='some_var=this.checked;'>

O con JavaScript:

cb = document.getElementsByClassName('messageCheckbox')[0]
cb.addEventListener('change', function(){some_var = this.checked})
 3
Author: Joe Iddon,
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-08 08:52:21

Usa esto:

alert($(".messageCheckbox").is(":checked").val())

Esto asume que las casillas de verificación a verificar tienen la clase "messageCheckbox", de lo contrario tendría que hacer una verificación si la entrada es el tipo de casilla de verificación, etc.

 2
Author: jackJoe,
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-22 10:57:42

$(document).ready(function() {
  var ckbox = $("input[name='ips']");
  var chkId = '';
  $('input').on('click', function() {
    
    if (ckbox.is(':checked')) {
      $("input[name='ips']:checked").each ( function() {
   			chkId = $(this).val() + ",";
        chkId = chkId.slice(0, -1);
 	  });
       
       alert ( $(this).val() ); // return all values of checkboxes checked
       alert(chkId); // return value of checkbox checked
    }     
  });
});
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>
<input type="checkbox" name="ips" value="12520">
<input type="checkbox" name="ips" value="12521">
<input type="checkbox" name="ips" value="12522">
 2
Author: Marinha do Nascimento,
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-10 15:16:59

Si estás usando Interfaz de usuario semántica React, data se pasa como segundo parámetro al evento onChange.

Por lo tanto, puede acceder a la propiedad checked de la siguiente manera:

<Checkbox label="Conference" onChange={(e, d) => console.log(d.checked)} />
 0
Author: Dave Clark,
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 14:11:52

En mi proyecto, suelo usar estos fragmentos:

var type[];
$("input[name='messageCheckbox']:checked").each(function (i) {
                type[i] = $(this).val();
            });

Y funciona bien. La mejor consideración.

 -3
Author: VanThaoNguyen,
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-03 02:18:27