enbermudas
enbermudas

Reputation: 1615

Select value changes but visible option selected does not

I'm working with WordPress by overriding the cart-shipping.php file (WooCommerce). After filling a select with options:

<?php
if (strpos($chosen_method, 'pickup_') !== false) {
    printf('<li><select name="select" id="method_pickups" onchange="handlePickup()">');
    foreach ($select as $key => $value) {
        printf('<option value="'.$key.'">'.$value.'</option>');
    }
    printf('</select></li>');
}
?>

I want to set the selected value by getting one stored on the session storage using javascript like this:

document.addEventListener('DOMContentLoaded', () => {
    const method_pickups = document.querySelector('#method_pickups');
    method_pickups.value = sessionStorage.getItem('method_pickups_soda');
    handlePickup();
});

const handlePickup = () => {
    const method_pickups = document.querySelector('#method_pickups');
    const billing_pickups = document.querySelector('#billing_pickups');
    sessionStorage.setItem('method_pickups_soda', method_pickups.value);

    if (!window.location.href.includes('carrito')) {
        billing_pickups.value = method_pickups.value;

        const index = method_pickups.selectedIndex;
        const display = document.querySelector('#display_pickup');
        display.value = method_pickups.options[index].text;
    }
};

The problem is that even though the value its being changed (cause a simple console.log() displays the new value) it is visually the same option. What is going on in here?

Thanks in advance and sorry for my bad english.

Upvotes: 1

Views: 59

Answers (1)

enbermudas
enbermudas

Reputation: 1615

Well, the problem was about an ajax request being in process which prevented the change. In order to solve my problem I waited for it to be finished:

jQuery(document).ajaxStop(function () {
    const method_pickups = document.querySelector('#method_pickups');
    method_pickups.value = sessionStorage.getItem('method_pickups_soda');
    handlePickup();
});

Upvotes: 2

Related Questions