I have the following snippet of code (I'm using jQuery 1.4.2):
$.post('/Ads/GetAdStatsRow/', { 'ad_id': id }, function(result) {
$('#edit_ads_form tbody').prepend(result);
$(result).find('td.select-ad input').attr('checked','checked').click();
});
Assume that the post works correctly and returns a correct pre-built <tr>
with some <td>
s. Here's the weirdness: the $(result).find()
line finds the correct input (which is a checkbox, as it's the only input in the cell) and runs the chained click()
function correctly, but it REFUSES to set the box as checked, which I need to happen.
Here's a crazy twist, too... when I get super specific and change the $(result).find()
line to this (the id of the checkbox):
$('#ad_' + id).click();
It checks the box, but doesn't run the click()
function! If I set it to
$('#ad_' + id).attr('checked','checked').click();
it runs the click function as though the box were checked, but the box remains unchecked, and if I do
$('#ad_' + id).click().attr('checked','checked');
it does nothing at all.
What in the world could be the matter with this? I'm running out of hair....
Thanks!
Here's how I set my click event in the $(function())
call:
$('td.select-ad input').live('click',AdPreview.selectAd);
It works as is for all the other checkboxes, and the newly-added checkbox does indeed work if clicked by hand.
After some digging I discovered that this:
$('#ad_' + id).click();
actually does call my click function in addition to checking the box. However, when the click function is called (I've already checked to make sure that input
is the correct checkbox and it is),
var input = $(this);
console.log(input.is(':checked'));
the log returns false, even though the box is actually checked! GAH WTF
I think it's because you're doing your find on some html which isn't in the DOM.
$.post('/Ads/GetAdStatsRow/', { 'ad_id': id }, function(result) {
// the "result" html is copied into the DOM
$('#edit_ads_form tbody').prepend(result);
// now you're doing a find on some HTML which isn't in the DOM.
$(result).find('td.select-ad input').attr('checked','checked').click();
});
That explains why doing the specific stuff works, to an extent. Here are the individual problems:
$('#ad_' + id).click();
This will click the box (making it get checked), but there are no events attached to it.
$('#ad_' + id).attr('checked','checked').click();
This sets the attribute to checked, and then clicks it, unchecking it straight away.
http://www.electrictoolbox.com/check-uncheck-checkbox-jquery/
jQuery (or the browser's DOM? I forget) expect a true or false value for the "checked" attribute, despite the fact that in HTML-source-land it's "checked='checked'".
HTH.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With