Home > Software design >  Get the selected value from populating select options
Get the selected value from populating select options

Time:01-25

var regionOption = document.querySelector("#municipality");
var districtOption = document.querySelector("#districtName");
var provOption = document.querySelector("#region");

createOption(provOption, Object.keys(regions));

provOption.addEventListener('change', function() {
    createOption(regionOption, regions[provOption.value]);
});
regionOption.addEventListener('change', function() {
      createOption(districtOption, districts[regionOption.value]);
});
function createOption(dropDown, options) {
    dropDown.innerHTML = '';
        options.forEach(function(value) {
            dropDown.innerHTML  = '<option name="'   value   '">'   value   '</option>';
        });
};

CSS:

<select id="region" style="width: 125px;"></select>
<select id="municipality" style="width: 125px;"></select>
<select id="districtName" style="width: 125px;"></select>

So, I'm populating options for an empty select and I was wondering how to get the value of the selected option. I basically want to check if (select value = 'A' && another selecte value = 'B') { do something}

CodePudding user response:

Set the value attribute on each <option>:

<option value="'   value   '">

Then, simply check the value property on the <select>.

if (document.getElementById("region").value === 'A') {
    // ...
}
  • Related