Dynamically generated checkboxes don't get checked
I create my checkboxes dynamically.
I have one checkbox which is in the code (not created
dynamically). For my dynamically created checkboxes I clone
it and then change id and name:
- <div id="sample">
<div class="ui-checkbox">
<input id="checkboxsample" class="custom" type="checkbox" name="checkboxsample" data-iconpos="left">
<label id="labelsample" class="ui-btn ui-btn-icon-left ui-checkbox-off ui-corner-top ui-corner-bottom ui-controlgroup-last ui-btn-up-a" for="checkboxsample" data-corners="true" data-shadow="false" data-iconshadow="true" data-wrapperels="span" data-icon="checkbox-off" data-iconpos="left" data-theme="a">
</div>
</div>
I checked in Firebug what was dynamically created:
- <input id="checkbox0" class="custom" type="checkbox" name="checkbox0" data-iconpos="left" checked="checked">
<label id="label0" class="ui-btn ui-btn-icon-left ui-checkbox-off ui-corner-top ui-corner-bottom ui-controlgroup-last ui-btn-up-a" for="checkbox0" data-corners="true" data-shadow="false" data-iconshadow="true" data-wrapperels="span" data-icon="checkbox-off" data-iconpos="left" data-theme="a">
I think the code is ok.
I want to toggle to checked/unchecked my checkbox
if I click on it.
My JavaScript code to do it:
- //$('#mypage').on('pageload', function(e){
$(document).ready(function () {
$('input:checkbox').live('change', function () {
var $this = $(this);
elementid = $(this).attr('id');
alert(elementid);
if ($("#"+elementid).prop('checked')) {
// the checkbox was checked
$("#"+elementid).removeAttr('checked');
} else {
// the checkbox was unchecked
$("#"+elementid).attr('checked', 'checked');
}
});
});
At the beginning all checkboxes are checked.
I set a breakpoint and see that "if ($("#"+elementid).prop('checked'))"
was false for my checkbox in the code (id=sample) althoug it has a check mark.
For my dynamically generated checkboxes "if" branch into the right code:
$("#"+elementid).removeAttr('checked');
But nothing happens. The checkbox persists checked.
The id's my "$(document).ready(function () {"
code gets are right. I see it in my alert order
( alert(elementid); ).
But after a while all checkboxes where sudenly unchecked.
I can't understand it.
What's wrong?