简体   繁体   中英

Simulate Mouse Click on dropdown

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.

Eg

1) When auto-populated using my script:

2) When user selected:

在此处输入图片说明 在此处输入图片说明

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?

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM