0

I am following this other thread to get jQuery into my admin settings page: https://stackoverflow.com/questions/28248113/jquery-is-not-defined-in-wordpress-but-my-script-is-enqueued-properly

My settings page building function:

function buildSettingsPage() {
  require 'views/newCouponForm.php'; // pure html

  wp_enqueue_media();
  wp_enqueue_script('jquery');
  ?>

  <button>Test</button>

  <script>
    (function($) {
      $(document).ready(function() {
        $("button").click().css("color", "orange");
      });
    })(jQuery);
  </script>

  <continues... removed>

The button instantly appears with orange text and submits, causing the page to go white after a second. I see the url with query string parameters also at this point. I believe this means a post request (which I haven't handled yet) is executed.

When I comment the IIFE the problem goes away.

How can I prevent this behavior? The intended behavior is to have the button text turn orange and submit on click only.

Attempted:

  <script>
    (function($) {
      $(document).ready(function(e) {
        e.preventDefault();
        $("button").click().css("color", "orange");
      });
    })(jQuery);
  </script>


Uncaught TypeError: e.preventDefault is not a function
    at HTMLDocument.<anonymous> (options-general.php?page=fvc-settings:304)
    at i (load-scripts.php?c=0&load[]=jquery-core,jquery-migrate,utils&ver=5.1.1:2)
2

The .click() function triggers a click. This is why this is happening. After the click .css() runs and turns the button orange.

If you want to change the colour on click then, as clear from the documentation, the event handler needs to be passed as a callback function to .click(), not chained to it:

$(document).ready(function() {
    $("button").click(function() {
        e.preventDefault();
        $(this).css("color", "orange");
    });
});

Note that e.preventDefault(); is supposed to go in the event handler, not where you had it.

Also, I think it's worth pointing out that jQuery is unecessary for this, you can do it with 'vanilla' JS like so:

var buttons = document.querySelectorAll( 'button' );

for ( var i = 0; i < buttons .length; i++ ) {
    buttons[i].addEventListener( 'click', function( e ) {
        e.preventDefault();
        buttons[i].style.color = 'orange';
    }
}

Or, if you don't need to support IE:

document.querySelectorAll( 'button' ).forEach( function( el ) {
    el.addEventListener( 'click', function( e ) {
        e.preventDefault();
        el.style.color = 'orange';
    }
} );

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.