Tuesday, 20 August 2013

jQuery selector on elements added via jQuaery after document load

jQuery selector on elements added via jQuaery after document load

jQuery selector for elements added dynamically doesn't seem to work. Put
simply, I have a set of checkboxes that are added with a function. The PHP
creates an add(..) entry for each row of data to be added (in this case a
filename, comment and checkbox to remove it). These are added using a
hard-coded templates and this works fine. I won't post the add script, but
it generates entries like (amended for brevity)...
<tr>
<td class="cell-file"><a href="...">afile.jpg</a></td>
<td class="cell-comment">A comment</td>
<td class="cell-remove a-center last"><input type="checkbox"
id="...is_delete" name="...is_delete" value="1" class="removable"></td>
</tr>
On state change of another checkbox, I need to set all the dynamically
added checkboxes to checked (and disable a button), with the following...
function setAddButton(arg){
if(arg){
$('add-attachment').addClassName('disabled');
Event.stopObserving('add-attachment', 'click');
// Check all removable checkboxes
$('input.removable:checkbox').attr('checked', true);
}else{
$('add-attachment').removeClassName('disabled');
Event.observe('add-attachment', 'click',
orderAttachment.add.bind(orderAttachment));
}
}
The problem is that the selector $('input.removable:checkbox') comes back
null. I've tried various forms of this selector including
$('.removable:checkbox') & $('input:checkbox.removable') but nothing is
selected.
Various posts say this selector should work, but it doesn't. So I am
assuming this is because jQuery cannot 'see' the dynamically added
elements. I've read various posts on using .live() or .on(), but this is
about adding an event handler to dynamically added elements. I don't want
an event handler, I just want to be able to select and set the checked
attribute of the dynamically added checkboxes.
Any ideas?

No comments:

Post a Comment