1
votes

I am trying to add a class to an element when a payment option is selected on the checkout page of WooCommerce. Here is my code, just for testing using the console to get a response:

jQuery(document).ready(function() {
    jQuery("#payment_method_extra_payment_option").on( "click", function() {
        console.log('1');
    });
});

I am targeting the radio button which has this id name. It is not working.

I have also tried using click(), which also does not working.

I can get this code to work when targeting a piece of text outside the payment options. I don't understand why this does not work.

3

3 Answers

1
votes

I have managed to solve this by using:

jQuery(document).ajaxComplete(function () {...

Instead of

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

I have been able to addClasses now and also amend field validation based on chosen payment gateway.

0
votes

The payment options are probably added to the dom after document.ready. So the click event listener won't be added to that element. You should use the .on function in an event-delegation approach:

$( "#the_parent_of_the_payment_method_extra_payment_option" ).on( "click", "#the_payment_method_extra_payment_option", function() {
    console.log('1');
});

(The id's in this code sample are illustrative)

See this chapter for more information: http://api.jquery.com/on/#direct-and-delegated-events

0
votes

Got the same problem. This works on mine.

jQuery(document).ready(function(){
    jQuery(document).on('click', "#payment_method_extra_payment_option", function(){
        // do your code here
    });
});