How to call jQuery function when checkbox is checked by PHP?
15,175
Try to use prop
function for this,
Also you don't need to call function, you can create it by using jquery.on()
function like,
$(function(){
$(document).on('click','.display_checkbox',function(){
if($(this).prop('checked')) {
// do stuff....
} else {
// do stuff....
}
});
});
And then remove onclick="checkbox_click(this);"
from your html checkbox element
Updated
To initialize it on document ready
$(function(){
$('.display_checkbox').each(function(){
if($(this).prop('checked')) {
// do stuff....
} else {
// do stuff....
}
});
});
Author by
user1448031
Updated on June 04, 2022Comments
-
user1448031 almost 2 years
Here is my PHP code:
<?php if (isset($mod['display']) && ($mod['display'] == "1")) { ?> <input class="display_checkbox" type="checkbox" name="chk[<?php echo $row; ?>][display]" value="1" checked="checked" onclick="checkbox_click(this);" /> <?php } else { ?> <input class="display_checkbox" type="checkbox" name="chk[<?php echo $row; ?>][display]" value="1" onclick="checkbox_click(this);" /> <?php } ?>
jQuery:
function checkbox_click(current) { if($(current).is(':checked')) { // do stuff.... } else { // do stuff.... } }
In the above code, when
$mod['display']
is true, the checkbox is checked but it does not invokecheckbox_click()
function. I triedonchange=
instead ofonclick=
but it does not seem to have any effect. I need to keep theonclick
oronchange
in the field. -
user1448031 almost 11 yearsNo, it's still not working for my purpose. It's doing the same thing as with my original function. When checkbox is checked by PHP, it is not invoking the function. It only calls the function when I manually click the checkbox.
-
user1448031 almost 11 yearsNo still does not seem to have any effect with PHP selection.
-
user1448031 almost 11 yearsThis now seems to work with PHP selection but it now fails when I manually click on the checkboxes- total opposite of what was happening with my initial code. To resolve this, if I keep my original function plus keep
onclick=...
and also include your above code, it works perfectly but this will then add redundant codes in the page. -
user1448031 almost 11 yearsYes I think so. I've updated the answer above with what has worked for me. Thanks for your help!!