'jQuery.on() does not work in WordPress admin panel

I'm writing my own WordPress(4.1.4) plugin which uses some JavaScript code in admin panel.

The first issue is $ object is undefined, so I use jQuery instead.

Now, I want to handle click on the button using jQuery:

jQuery(function(){
    jQuery(".my-button").on("click", function(){
        alert("OK");
    });
});

Unfortunately, this simple code does not work, but if I try to use this:

jQuery(function(){
    jQuery(".my-button").click(function(){
        alert("OK");
    });
});

it works fine.

At first, I thought that jQuery version is too old, but when I checked it, I got 1.11.1.

So I don't understand why the jQuery.on() does not work in my case.



Solution 1:[1]

Make sure you code is running at the end of the document by running <?php wp_enqueue_script( $handle, $src, $deps, $ver, $in_footer ); ?>, then setting the $in_footer argument to true. Then the on function should work as expected. I've tested in WP version 4.2.1, but it should still work in your 4.1.4 environment. This code will also allow you to use the $.

(function($){
    $(".my-button").on("click", function(e){
        e.preventDefault();
        alert("OK");
    });
}(jQuery));

Solution 2:[2]

I had same problem :/ my code:

(function ($) {
    "use strict";

    jQuery('.theme_data_sync').click(function (e) {
        jQuery('.theme_data_sync').addClass('xxx')
    })

})(jQuery);

at first, i thought there is jquery problem! but at the end after half an hour Checking my codes, 'wp_enqueue_script' was the cause! i put the 'true' at the end of 'wp_enqueue_script' for loading scripts in footer; it worked for me

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1
Solution 2 honk31