questions

How to change a background when checking a box in jquery when a script loads

Rate this post

I’m having problems with my code. It’s a checkbox in an Advanced Custom Fields block that’s suppose to change the color of a background. When you click on the checkbox, it doesn’t change the color. I know that ACF blocks have to use $(document).on('change', function () and I am able to do other functions that work except clicking on a checkbox.

My code:

jQuery(document).ready(function ($) {
   $(document).on('change', function () {
      if ($("input#acf-block_60160a1a4dc32-field_5f8cf27e7c048-two_img_left_set_featured_img").is(':checked')) {
        $(".acf-field-5f8cf27e7c048").css({'background':'black'});
      } else {
        $(".acf-field-5f8cf27e7c048").css({'background':'white'});
      }
   });
});

 

✔️Solution:

Can’t say I have any experience with wordpress, but from a general view, having a single change listener for the entire document could have unintended consequences, since anything the fires a change (other inputs, selects, textareas, etc) will run this code. Have you tried providing a selector argument with the .on() method to better scope this handler?

$(document).on(`change`, `input#acf-block_60160a1a4dc32-field_5f8cf27e7c048-two_img_left_set_featured_img`, function () {
  $(`.acf-field-5f8cf27e7c048`).css(`background`, $(this).is(`:checked`) ? `black` : `white`);
});

Leave a Reply

Your email address will not be published.

Back to top button