Pregunta

¿Cómo atrapar a comprobar / desmarque caso de <input type="checkbox" /> con jQuery?

¿Fue útil?

Solución

<input type="checkbox" id="something" />

$("#something").click( function(){
   if( $(this).is(':checked') ) alert("checked");
});

Editar: Hacer esto no cogerá cuando la casilla de verificación cambia por otras razones que un clic, como usar el teclado. Para evitar este problema, escuchar changeinstead de click.

Para marcando / desmarcando mediante programación, echar un vistazo a Por qué no es mi evento de cambio de casilla de verificación activa?

Otros consejos

El clic afectará una etiqueta si tenemos una conectada a la casilla de entrada?

Creo que es mejor usar la función .Cambiar ()

<input type="checkbox" id="something" />

$("#something").change( function(){
  alert("state changed");
});

Para usar jQuery 1.7+:

$('input[type=checkbox]').on('change', function() {
  ...
});

En mi experiencia, he tenido que aprovechar currentTarget del evento:

$("#dingus").click( function (event) {
   if ($(event.currentTarget).is(':checked')) {
     //checkbox is checked
   }
});

utilizar el evento clic para una mejor compatibilidad con MSIE

$(document).ready(function() {
    $("input[type=checkbox]").click(function() {
        alert("state changed");
    });
});

Este código hace lo que su necesidad:

<input type="checkbox" id="check" >check it</input>

$("#check").change( function(){
   if( $(this).is(':checked') ) {
        alert("checked");
    }else{
        alert("unchecked");
   }
});

Además, puede comprobarlo en jsFiddle

$(document).ready(function(){
    checkUncheckAll("#select_all","[name='check_boxes[]']");
});

var NUM_BOXES = 10;
// last checkbox the user clicked
var last = -1;
function check(event) {
  // in IE, the event object is a property of the window object
  // in Mozilla, event object is passed to event handlers as a parameter
  event = event || window.event;

  var num = parseInt(/box\[(\d+)\]/.exec(this.name)[1]);
  if (event.shiftKey && last != -1) {
    var di = num > last ? 1 : -1;
    for (var i = last; i != num; i += di)
      document.forms.boxes['box[' + i + ']'].checked = true;
  }
  last = num;
}
function init() {
  for (var i = 0; i < NUM_BOXES; i++)
    document.forms.boxes['box[' + i + ']'].onclick = check;
}

HTML:

<body onload="init()">
  <form name="boxes">
    <input name="box[0]" type="checkbox">
    <input name="box[1]" type="checkbox">
    <input name="box[2]" type="checkbox">
    <input name="box[3]" type="checkbox">
    <input name="box[4]" type="checkbox">
    <input name="box[5]" type="checkbox">
    <input name="box[6]" type="checkbox">
    <input name="box[7]" type="checkbox">
    <input name="box[8]" type="checkbox">
    <input name="box[9]" type="checkbox">
  </form>
</body>
Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top