Andrew
Andrew

Reputation: 552

React, how to change dropdown menu option? JQuery?

Here is the HTML code;

    <div class="gl-native-dropdown" autoid="shippingAddress-stateCode" optionsautoid="shippingAddress-stateCode-options" data-auto-id="shippingAddress-stateCode">
        <div class="gl-native-dropdown__select">
<span class="gl-native-dropdown__select-label">
<span class="gl-native-dropdown__select-label-text">State</span>
<span class="gl-native-dropdown__select-label-hint gl-form-asterisk"></span></span>
            <svg class="gl-icon gl-native-dropdown__select-icon">
                <use xlink:href="#dropdown"></use>
            </svg>
        </div>
        <select class="gl-native-dropdown__select-element">
            <option></option>
            <option>AA Military</option>
            <option>AE Military</option>
            <option>AP Military</option>
            <option>Alabama</option>
            <option>Alaska</option>
            <option>Nebraska</option>
            <option>Nevada</option>
            <option>New Hampshire</option>
            <option>New Jersey</option>
            <option>New Mexico</option>
            <option>New York</option>
        </select>
    </div>

Here is what I have tried;

let selectedValue = $('select[class="gl-native-dropdown__select-element"] > option:contains(“New York")').val();

    let select = document.querySelectorAll('.gl-native-dropdown__select-element')[0];
    select.value = selectedValue;
    var nativeInputValueSetter = Object.getOwnPropertyDescriptor(window.HTMLSelectElement.prototype, "value").set;
    nativeInputValueSetter.call(select, selectedValue);
    var ev2 = new Event('change', { bubbles: true});
    select.dispatchEvent(ev2);

But my code does not work, the dropdown menu text is not changed to "New York"

Anything helps, all is appreciated.

I do not know how to fix my code (not HTML code), and I know I am close.

Thanks.

Upvotes: 1

Views: 524

Answers (1)

Abdelrahman Gobarah
Abdelrahman Gobarah

Reputation: 1589

let selectedValue = 'New York';

    let select = document.querySelectorAll('.gl-native-dropdown__select-element')[0];
    select.value = selectedValue;
    var nativeInputValueSetter = Object.getOwnPropertyDescriptor(window.HTMLSelectElement.prototype, "value").set;
    nativeInputValueSetter.call(select, selectedValue);
    var ev2 = new Event('change', { bubbles: true});
    select.dispatchEvent(ev2);

Upvotes: 5

Related Questions