1

My Wordpress theme interacts with WooCommerce so that when a user selects a specific product variable from a drop-down a particular price is shown for their region.

This works fine when a user manually selects the drop-down, however, I'm trying to speed up the process by pre-selecting the appropriate option for the user based on a browser cookie (or lack of one).

For instance, if the user hasn't entered their region their browser will not have a cookie I've named "pc-entered" and the following jQuery script will run:

$(function() {
    $('ul li.product').each( function() {
        /*If no region set by cookie*/
        if( document.cookie.indexOf("pc-entered=") < 0) {
            /*Set downdown to generic*/ 
            $(this).find("#pa_region").val('generic');  
        }
    });
}); 

This works, successfully pre-selecting the correct 'generic' dropdown option automatically.

Unfortunately, and this is where I'm stuck - although the dropdown is correct the price isn't auto-populating like it does when a user manually selects their region.

E.g.

1) When auto-populated using my script:

2) When user selected:

enter image description here enter image description here

I've tried replacing this in my script:

$(this).find("#pa_region").val('generic');

With the options listed on this thread, however, they don't seem to work in this case. I've also tried firing the script after all other scripts on the page and even delaying the script running with a timeout function but nothing seems to be working.

My test site is here.

TLDR - Why is my jQuery script not populating the price?

Dan382
  • 976
  • 6
  • 22
  • 44

1 Answers1

1

With $(this).find("#pa_region").val('generic'); you are only changing the HTML value (text) of dropdown.

You need to attach the event handler which will trigger the change to the function where you change the value.

function changeValue(){
  $("#pa_region").val('generic');
  $("#pa_region").trigger('change');
}

$( "#pa_region" ).change(function() {
  console.log( "Handler for .change() called." );
});

This is the way on how to solve it.

I also made a JSFiddle so you can test it.

Dino
  • 7,779
  • 12
  • 46
  • 85
  • Thanks for that, it makes sense that I'm only changing the HTML. Quick question, in your JSFiddle the function is triggered by clicking the button. How could I get the function to trigger when the page loads whilst retaining my existing each function? – Dan382 Jun 06 '17 at 21:56
  • 1
    If I understood you correctly, you could just add the trigger in document.ready function. https://jsfiddle.net/2rkkb3jh/4/ – Dino Jun 07 '17 at 07:38