Domanda

Come faccio a catturare controllare / deselezionare evento di <input type="checkbox" /> con jQuery?

È stato utile?

Soluzione

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

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

Modifica: Fare questo non prenderà quando la casella di controllo cambia per ragioni diverse da uno scatto, come l'utilizzo della tastiera. Per evitare questo problema, ascoltare changeinstead di click.

Per il controllo / deselezionando di programmazione, dare un'occhiata a Perché non è il mio cambiamento casella evento innescato?

Altri suggerimenti

Il click interesserà un'etichetta se abbiamo uno attaccato alla casella di input?

Credo che sia meglio usare la funzione .Per passare ()

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

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

Per uso JQuery 1.7+:

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

Nella mia esperienza, ho dovuto sfruttare currentTarget dell'evento:

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

utilizzare l'evento click per la massima compatibilità con MSIE

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

Questo codice fa che cosa il vostro bisogno:

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

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

Inoltre, è possibile controllare su 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>
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top