How to trigger selected option event?

Asked by At

I am trying to write some Javascript (not Jquery) that when the address dropdown field is clicked it will trigger an event to check the value in the 'ship state' field.

<script>

var addressDropdown = document.querySelector('#address-id');

var shipstateDropdown = document.querySelector('#shipstate-id');

var SelectedShipState;

addressDropdown.addEventListener('click', (addressEvent) => {
if (shipstateDropdown.options[shipstateDropdown.selectedIndex].value === "CA") {
    SelectedShipState = "CA";
    RunRule();
        }
})

</script>

1 Answers

0
The1987 On

I resolved my issue. I first had to set the event handler for the address drop down which when this occurred it triggered a function. That function then gets the value from the ship state dropdown.

I also added in a setTimeout because the act of triggering the address handler was grabbing the ship state before the value could arrive resulting in a value that was delayed or null.

// Global defined variables //
var SelectedShipState
var selectElement = document.getElementById('ship-state-id');
var addressBook = document.getElementById('address-book-id');

// Change Event: When an address from the address book is selected ...
addressBook.addEventListener('change', (addressEvent) => {

// ... run this function to get the ship state.
setTimeout(addressFunction, 1000);
    })

// When this function runs ...
function addressFunction() {

// ... get the value from the ship state select option.
SelectedShipState = this.selectElement.options[selectElement.selectedIndex].value;
RunRule();
    }

// Change Event : Get the option each time it is selected //
selectElement.addEventListener('change', (changeEvent) => {
SelectedShipState = `${changeEvent.target.value}`;
RunRule();
})

function RunRule () {
// do something ...
}