jQuery instantly executes (a button click and css change) on load

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)

Read more here:: jQuery instantly executes (a button click and css change) on load

Leave a Reply

Your email address will not be published. Required fields are marked *