The JS function works in console, but not when loaded from a file

I cannot figure out why this code will not run from the .js file but will run from the console.

function cartCalculateDaysOfRental() {

var cartItem = $( “.cart_item” );

$( cartItem ).each(function() {

// calculate day between rental dates

var start = $(‘td.product-name dd.variation-RentalDates’:wink:.text();

start = start.replace(new RegExp(“/”,”g”:wink:, ‘-‘:wink:;

start_array = start.split(“-“:wink:;

start_array[2] = parseInt( start_array[2] )+2000;

fixed_date_start = start_array[2]+”-“+start_array[0]+”-“+start_array[1];

var end = $(‘td.product-name dd.variation–‘:wink:.text();

end = end.replace(new RegExp(“/”,”g”:wink:, ‘-‘:wink:;

end_array = end.split(“-“:wink:;

end_array[2] = parseInt(end_array[2])+2000;

var fixed_date_end = end_array[2]+”-“+end_array[0]+”-“+end_array[1];

// var rentalTotal = ($(‘dd.variation-PartialPayment p span.amount:first-child’:wink:.text());

var diff = new Date(fixed_date_end) – new Date(fixed_date_start);

var hourly_time = diff/(60*60*1000);

var days = hourly_time/24;

var rentDays = days + 1;

// $( rentDays ).appendTo( ‘td.product-name dt.caption.rdates’ );

$( ‘dt.caption.rdates:contains(“Total Rental Days:”:wink:’ ).append( rentDays );

});

}

$(document).ready(function() {

cartCalculateDaysOfRental();

});

JS file is loaded using wp_enqueue_script()

No errors showing in the console.

  • Majid
    • Recruit

    Hi Luke,

    I hope you are doing great today :slight_smile:

    Make sure you enqueue your JS script using the wp_enqueue_script function like this

    wp_enqueue_script( 'test', get_stylesheet_directory_uri() . '/assets/js/test.js', array( 'jquery' ), false, false );

    And wrap the whole jQuery code inside this

    (function($) {
    //your code here
    })(jQuery);

    Once that done, you can check if the script is loaded by viewing the page source “CTRL + U” on chrome, or by using

    console.log()

    somewhere inside your JS file.

    Cheers,

    Majid