Search code examples
jquerywordpresswoocommercereferenceerror

Wordpress: Uncaught ReferenceError: myfunction is not defined


This is the javascript I enqueue en wordpress but I have this error. "Uncaught ReferenceError: myfunction is not defined ".

(function($) {
    function myfunction(bf) {
        if(bf.checked)
            var text1 = document.getElementById("shipping_first_name").value;
        else
            text1='';
        document.getElementById("billing_first_name").value = text1;
        };
})(jQuery);

Also I tried with this code too.

(function($) {
    jQuery(document).ready(function($) {

        function myFunction(bf) {
            if(bf.checked)
                var text1 = document.getElementById("shipping_first_name").value;
            else
                text1='';

            document.getElementById("billing_first_name").value = text1;
            }
    });
})(jQuery);

Enqueue:

function my_scripts_method() {
    wp_enqueue_script(
        'custom-script',
        get_template_directory_uri() . '/js/shipping.js',
        array( 'jquery' ),
        false,
        '1.0',
        true
    );
}

add_action( 'wp_enqueue_scripts', 'my_scripts_method' );

Solution

  • A method defined inside a closure is only accessible inside the closure itself.

                (function(){
                    /* This is called closure
                     All code here is solely on clouser
                    */
                }())
    

    To access the method you can alter the closure as follows

                (function(){
                    window.myfunction = function(bf){
                        /*...*/
                    }
                }())