Ressources en ligne: Setting “checked” for a checkbox with jQuery?
1 2 3 |
<td class="col-damaged col-boolean" onClick="$(this).booleanIntent(event);"> <input type="checkbox" id="product_00001_damaged" name="product_00001" /> </td> |
ATTENTION: l’utilisation de $(this)
dans la fonction pour récupérer l’élément cliqué empêche le clic sur l’élément <input type="checkbox" />
lui-même! On préférera utiliser event.target
pour cibler l’élément cliqué.
Code non commenté
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 |
$.fn.booleanIntent = function(event){ const $_TARGET = $(event.target); if ( $_TARGET.is('input') ) { return false; } else { const $_INPUT = $_TARGET.children('input'), CHECKED_VALUE = $_INPUT.prop('checked'); if ( CHECKED_VALUE != true ) { $_INPUT.prop('checked', true); } else { $_INPUT.prop('checked', false); } } } |
Code commenté
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 |
$.fn.booleanIntent = function(event){ const $_TARGET = $(event.target); if ( $_TARGET.is('input') ) { console.log('is input'); return false; } else { console.log('is not input'); const $_INPUT = $_TARGET.children('input'), CHECKED_VALUE = $_INPUT.prop('checked'); console.log('CHECKED_VALUE: '+CHECKED_VALUE); if ( CHECKED_VALUE != true ) { console.log('input is not checked, so we check it'); $_INPUT.prop('checked', true); } else { console.log('input is checked, so we uncheck it'); $_INPUT.prop('checked', false); } } } |