Comment basculer l'état de vérification d'un élément d'entrée radio sur le clic?

Comment (un) vérifier un élément d'entrée radio sur le clic de l'élément ou son conteneur?

J'ai essayé le code ci-dessous, mais il ne coupe pas la radio.

HTML:

<div class="is"> <label><input type="radio" name="check" class="il-radio" /> Is </label> <img src="picture" /> </div> 

JQuery:

 $(".is label, .is ").click(function () { if (!$(this).find(".il-radio").attr("checked")) { $(this).find(".il-radio").attr("checked", "checked"); } else if ($(this).find(".il-radio").attr("checked") == "checked") { $(this).find(".il-radio").removeAttr("checked"); } }); 

Vous devez empêcher le comportement par défaut. Actuellement, sur le clic, ce qui suit se produit:

  1. click feux d'événement de click pour le conteneur ( div.is ).
  2. click feux d'événement pour l'étiquette.
  3. Puisque votre fonction bascule un état, l'auditeur d'événements s'appelle deux fois, le résultat est que rien ne semble se produire.

Code corrigé ( http://jsfiddle.net/nHvsf/3/ ):

 $(".is").click(function(event) { var radio_selector = 'input[type="radio"]', $radio; // Ignore the event when the radio input is clicked. if (!$(event.target).is(radio_selector)) { $radio = $(this).find(radio_selector); // Prevent the event to be triggered // on another element, for the same click event.stopImmediatePropagation(); // We manually check the box, so prevent default event.preventDefault(); $radio.prop('checked', !$radio.is(':checked')); } }); $(".il-radio").on('change click', function(event) { // The change event only fires when the checkbox state changes // The click event always fires // When the radio is already checked, this event will fire only once, // resulting in an unchecked checkbox. // When the radio is not checked already, this event fires twice // so that the state does not change this.checked = !this.checked; }); 

Les boutons radio ne décochez pas, vous devez utiliser une case à cocher (type = 'case à cocher')

Utilisez uniquement html, même fonctionnalité

 <label for="rdio"><input type="radio" name="rdio" id="rdio" class="il-radio" /> Is </label>