mercredi 24 décembre 2014

How to detect a checkbox click in jQuery

I cannot detect when and which checkbox gets clicked from script below:


HTML Snippet:



<label for="checkbox[1]"><input type="checkbox" name="checkbox[1]" id="checkbox[1]" class="detectThisChange" value="10.00" checked=""> Amount $10.00</label>
<label for="checkbox[2]"><input type="checkbox" name="checkbox[2]" id="checkbox[2]" class="detectThisChange" value="20.00" checked=""> Amount $20.00</label>
<label for="checkbox[3]"><input type="checkbox" name="checkbox[3]" id="checkbox[3]" class="detectThisChange" value="30.00" checked=""> Amount $30.00</label>


jQuery Snippet:



$('.detectThisChange').change(function(event){
var targetID = triggerEvent.target.id; // get the id that triggered the event
var posStart = targetID.indexOf('[') + 1;
var posEnd = targetID.indexOf(']');
var i = targetID.substring(posStart, posEnd); // get the index of the id that triggered the event

if ( $('#checkbox\\['+ i +'\\]').prop('checked') != true ) {
alert('checkbox ' + i + ' was checked');
}
else {
alert('checkbox ' + i + ' was unchecked');
}

});




Aucun commentaire:

Enregistrer un commentaire