Brad
Brad

Reputation: 479

Stop a function if page has a class

I have a simple function that appends the shipping details, to billing details in my woocommerce checkout. However I want this function to stop firing once a class has ben added to a div.

function billingclick() {
    $('#billing_first_name').val($('#shipping_first_name').val());
    $('#billing_last_name').val($('#shipping_last_name').val());    
};

$('.wpmc-ripple.wpmc-billing').on('click', function(e) {
    billingclick();
}); 

I can't use the one click function, as validation breaks this.

Is there a way I can stop the function if the div class is added?

e.g if .wpmc-step-shipping has the class current, stop the billingclick() function.

    if (!$(".wpmc-step-shipping").hasClass("current")) {
        // function here
    }

Thank you

Upvotes: 1

Views: 67

Answers (3)

Brett Caswell
Brett Caswell

Reputation: 1504

As the other answers said, you can perform that check in your click handler:

//this should probably be renamed to be updateBillingWithShipping
function billingclick() {
    $('#billing_first_name').val($('#shipping_first_name').val());
    $('#billing_last_name').val($('#shipping_last_name').val());    
};

$('.wpmc-ripple.wpmc-billing').on('click', function(e) {
    if (!$(".wpmc-step-shipping").hasClass("current")) {
        billingclick();
    }
}); 

You could also remove the event handler on $('.wpmc-ripple.wpmc-billing')

You could also disable the '.wpmc-ripple.wpmc-billing' control.

  • This is typically something you would describe on your component view since it is control state that reflects on state of another control (represented as a class).

Upvotes: 1

Rory McCrossan
Rory McCrossan

Reputation: 337714

It seems like you're trying to remove the click handler. While this is possible, you need to know exactly when the class is added to the relevant element, which is not always possible, nor simple.

A easier solution is to instead place your if condition within the billingclick() function and only update the val() of the required elements when the class is not present. Try this:

function billingclick() {
  if (!$(".wpmc-step-shipping").hasClass("current")) {
    $('#billing_first_name').val($('#shipping_first_name').val());
    $('#billing_last_name').val($('#shipping_last_name').val());
  }
};

$('.wpmc-ripple.wpmc-billing').on('click', billingclick);

Upvotes: 2

Ahmed Tag Amer
Ahmed Tag Amer

Reputation: 1422

Your code should look like this :

function billingclick() {
  if (!$(".wpmc-step-shipping").hasClass("current")) {
    $('#billing_first_name').val($('#shipping_first_name').val());
    $('#billing_last_name').val($('#shipping_last_name').val());  
  }  
};

$('.wpmc-ripple.wpmc-billing').on('click', function(e) {
    billingclick();
}); 

Perform the if condition first inside your function.

Upvotes: 1

Related Questions